You are on page 1of 6

Object Oriented Programming through JAVA Unit – 3

Lecture Notes – 32
Keywords in Exception Handling
There are 5 keywords used in java exception handling. They are
1. try
2. catch
3. finally
4. throw
5. throws
Java try block
Java try block is used to enclose the code that might throw an exception. It must be
used within the method. Java try block must be followed by either catch or finally block.
Syntax of java try-catch:
try{
//code that may throw exception
}catch(Exception_class_Name ref){}
Syntax of try-finally block
try{
//code that may throw exception
}finally{}
Java catch block:
Java catch block is used to handle the Exception. It must be used after the try block
only. You can use multiple catch block with a single try.
Problem without exception handling:
public class Testtrycatch1{
public static void main(String args[]){
int data=50/0; //may throw exception
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
As displayed in the above example, rest of the code is not executed (in such case, rest
of the code... statement is not printed).

M. Satish (IT)
Object Oriented Programming through JAVA Unit – 3

There can be 100 lines of code after exception. So all the code after exception will not
be executed.
Solution by exception handling:
Let's see the solution of above problem by java try-catch block.
public class Testtrycatch2{
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){System.out.println(e);}
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero rest of the code...

Usage of try-catch Statements:


class DivByZero
{
public static void main(String args[]) {
try
{
System.out.println(3/0);
System.out.println(“Please print me.”);
} catch (ArithmeticException exc)
{
//Division by zero is an ArithmeticException
System.out.println(exc);
}
System.out.println(“After exception.”);
}
}

M. Satish (IT)
Object Oriented Programming through JAVA Unit – 3
Catching Exceptions: Multiple Catch
class MultipleCatch
{
public static void main(String args[])
{
try {
int den = Integer.parseInt(args[0]);
System.out.println(3/den);
} catch (ArithmeticException exc) {
System.out.println(“Divisor was 0.”);
} catch (ArrayIndexOutOfBoundsException exc2) {
System.out.println(“Missing argument.”);
}
System.out.println(“After exception.”);
}
}

Catching Exceptions: Nested try's


class NestedTryDemo {
public static void main(String args[]){
try {
int a = Integer.parseInt(args[0]);
try {
int b = Integer.parseInt(args[1]);
System.out.println(a/b);
} catch (ArithmeticException e)
{
System.out.println(“Div by zero error!");
} } catch (ArrayIndexOutOfBoundsException)
{
System.out.println(“Need 2 parameters!");
}
}
}

M. Satish (IT)
Object Oriented Programming through JAVA Unit – 3
Catching Exceptions: Nested try's with methods
class NestedTryDemo2
{
static void nestedTry(String args[])
{
try {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
System.out.println(a/b);
} catch (ArithmeticException e) {
System.out.println("Div by zero error!");
}
}
public static void main(String args[]){
try {
nestedTry(args);
} catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Need 2 parameters!");
}
}
}

Throwing Exceptions (throw):


So far, we were only catching the exceptions thrown by the Java system. In fact, a
user program may throw an exception explicitly: throw ThrowableInstance;
ThrowableInstance must be an object of type Throwable or its subclass. Once an
exception is thrown by: throw ThrowableInstance;
• the flow of control stops immediately
• the nearest enclosing try statement is inspected if it has a catch statement that
matches the type of exception:
• if one exists, control is transferred to that statement
• otherwise, the next enclosing try statement is examined
• if no enclosing try statement has a corresponding catch clause, the default
exception handler halts the program and prints the stack.
M. Satish (IT)
Object Oriented Programming through JAVA Unit – 3

throws Declaration:
If a method is capable of causing an exception that it does not handle, it must specify
this behavior by the throws clause in its declaration:
type name(parameter-list) throws exception-list
{

}
where exception-list is a comma-separated list of all types of exceptions that a method
might throw. All exceptions must be listed except Error and RuntimeException or any of
their subclasses, otherwise a compile-time error occurs.

Use of throws keyword in Java:


1. The throws keyword is used in method declaration, in order to explicitly specify the
exceptions that a particular method might throw. When a method declaration has one or more
exceptions defined using throws clause then the method-call must handle all the defined
exceptions.
2. When defining a method you must include a throws clause to declare those
exceptions that might be thrown but doesn’t get caught in the method.
3. If a method is using throws clause along with few exceptions then this implicitly
tells other methods that – “ If you call me, you must handle these exceptions that I throw”.

finally Block:
1. A finally statement must be associated with a try statement. It identifies a block of
statements that needs to be executed regardless of whether or not an exception occurs within
the try block.
2. After all other try-catch processing is complete, the code inside the finally block
executes. It is not mandatory to include a finally block at all, but if you do, it will run
regardless of whether an exception was thrown and handled by the try and catch parts of the
block.
3. In normal execution the finally block is executed after try block. When any
exception occurs first the catch block is executed and then finally block is executed.
4. An exception in the finally block, exactly behaves like any other exception.
5. The code present in the finally block executes even if the try or catch block
contains control transfer statements like return, break or continue.
M. Satish (IT)
Object Oriented Programming through JAVA Unit – 3
Syntax of Finally block:
try
{
//statements that may cause an exception
}
finally
{
//statements to be executed
}
Cases when the finally block doesn’t execute
The circumstances that prevent execution of the code in a finally block are:
– The death of a Thread
– Using of the System. exit() method.
– Due to an exception arising in the finally block.

M. Satish (IT)

You might also like