Page 1 of 13
Class Notes on Exception handling (Week - 8)
Contents: - Exception handling basics, different types of exception classes, use of try & catch with throw, throws &
finally, creation of user defined exception classes.
Exception Handling in Java
The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the
runtime errors so that normal flow of the application can be maintained.
In this Note, we will know about exception, its type and the difference between checked and unchecked exceptions.
Exception
 Dictionary Meaning:Exception is an abnormal condition.
 In java, exception is an event that disrupts the normal flow of the program. It is an object which is thrown at
runtime.
An exception is a problem that arises during the execution of a program. An exception can occur for many different
reasons, including the following:
 A user has entered invalid data.
 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications, or the JVM has run out of memory.
Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that
have failed in some manner.
To understand how exception handling works in Java, you need to understand the three categories of exceptions:
 Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot
be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception
occurs. These exceptions cannot simply be ignored at the time of compilation. The classes that extend
Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException,
SQLException etc. Checked exceptions are checked at compile-time.
 Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by
the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.
The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-
time rather they are checked at runtime.
 Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the
programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For
example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation. Error is
irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Exception Handling
Exception Handling is a mechanism to handle runtime errors.
Page 2 of 13
Advantage of Exception Handling
The core advantage of exception handling is that normal flow of the application is maintained. Exception normally
disrupts the normal flow of the application that is why we use exception handling. Let's take a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
Suppose there is 9 statements in your program and there occurs an exception at statement 5, rest of the code will not
be excecuted i.e. statement 6 to 9 will not run. If we perform exception handling, rest of the exception will be executed.
That is why we use exception handling.
Common scenarios of Exception Handling where exceptions may occur
There are given some scenarios where unchecked exceptions can occur. They are as follows:
1) Scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
1. int a=50/0; // ArithmeticException
2) Scenario where NullPointerException occurs
If we have null value in any variable, performing any operation by the variable occurs an NullPointerException.
1. String s=null;
2. System.out.println(s.length()); // NullPointerException
3) Scenario where NumberFormatException occurs
The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable that have
characters, converting this variable into digit will occur NumberFormatException.
1. String s="abc";
2. int i=Integer.parseInt(s); // NumberFormatException
4) Scenario where ArrayIndexOutOfBoundsException occurs
If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown below:
1. int a[]=new int[5];
2. a[10]=50; // ArrayIndexOutOfBoundsException
Page 3 of 13
Use of try-catch block in Exception handling:
Five keywords used in Exception handling:
1. try
2. catch
3. finally
4. throw
5. throws
try block
Enclose the code that might throw an exception in try block. It must be used within the method and must be followed by
either catch or finally block.
Syntax of try with catch block
1. try{
2. ...
3. }catch(Exception_class_Name reference_variable_or_object){ … }
Syntax of try with finally block
1. try{
2. ...
3. }finally{}
catch block
Catch block is used to handle the Exception. It must be used after the try block.
Problem without exception handling
1. class Simple{
2. public static void main(String args[]){
3. int data=50/0;
4.
5. System.out.println("rest of the code...");
6. }
7. }
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
As displayed in the above example, rest of the code is not executed i.e. rest of the code... statement is not printed. Let's
see what happens behind the scene:
Page 4 of 13
What happens behind the code int a=50/0;
The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM provides a default
exception handler that performs the following tasks:
 Prints out exception description.
 Prints the stack trace (Hierarchy of methods where the exception occurred).
 Causes the program to terminate.
But if exception is handled by the application programmer, normal flow of the application is maintained i.e. rest of the
code is executed.
Solution by exception handling
1. class Simple{
2. public static void main(String args[]){
3. try{
4. int data=50/0;
5.
6. }catch(ArithmeticException e){System.out.println(e);}
7.
8. System.out.println("rest of the code...");
9. } // main ends
10. } // class ends
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code... statement is printed.
Multiple catch block
If you have to perform different tasks at the occrence of different Exceptions, use multple catch block.
Page 5 of 13
Rule 1: At a time only one Exception is occured and at a time only one catch block is executed.
Rule 2: All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come
before catch for Exception
class Excep4{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e){System.out.println("common task completed");}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
System.out.println("rest of the code...");
}
}
Output: (Compile time Error)
Excep4.java:8: exception java.lang.ArithmeticException has already been caught
catch(ArithmeticException e){System.out.println("task1 is completed");}
^
Excep4.java:9: exception java.lang.ArrayIndexOutOfBoundsException has already
been caught
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");
}
^
2 errors
Explanation
If you try to compile this program, you will receive an error message stating that the second and third catch statement is
unreachable(look at the error messages) because the exception has already been caught. Since ArithmeticExceptionis a
subclass of Exception, the first catch statement will handle all Exception-based errors, including ArithmeticException.
This means that the second and third catch statement will never execute. To fix the problem, reverse the order of the
catch statements or just put the catch(Exception e) statement at last.
Modified Program
class Excep4{
public static void main(String args[]){
try{
int a[]=new int[5];
//a[10]=90; if we uncomment this line then ArrayIndexOutOfBoundsException
a[5]=30/0; // generates ArithmeticException
}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(Exception e){System.out.println("common task completed");}
System.out.println("rest of the code...");
}
}
Output: task1 is completed
rest of the code...
Page 6 of 13
Nested try block:
try block within a try block is known as nested try block.
Why use nested try block?
Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause
another error. In such cases, exception handlers have to be nested
Syntax:
1. ....
2. try
3. {
4. statement 1;
5. statement 2;
6. try
7. {
8. statement 1;
9. statement 2;
10. }
11. catch(Exception e)
12. {
13. }
14. }
15. catch(Exception e)
16. {
17. }
18. ....
Example of nested try block
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
// int x=7/0; uncomment,then catch(Exception e) handled
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement”);
}catch(Exception e){System.out.println("All Exceptions handeled");}
System.out.println("normal flow..");
}
}
OUTPUT:
going to divide
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: 5
Page 7 of 13
other statement
normal flow..
finally block
The finally block is a block that is always executed. It is mainly used to perform some important tasks such as closing
connection, stream etc.
Note:Before terminating the program, JVM executes finally block(if any).
Note:finally must be followed by try or catch block.
Why use finally block?
 finally block can be used to put "cleanup" code such as closing a file,closing connection etc.
case 1
Program in case exception does not occur
1. class Simple{
2. public static void main(String args[]){
3. try{
4. int data=25/5;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8.
9. finally{System.out.println("finally block is always executed");}
10.
11. System.out.println("rest of the code...");
12. }
13. }
Output:5
finally block is always executed
rest of the code...
Page 8 of 13
case 2
Program in case exception occured but not handled
1. class Simple{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8.
9. finally{System.out.println("finally block is always executed");}
10.
11. System.out.println("rest of the code...");
12. }
13. }
Output:finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
case 3
Program in case exception occured and handled
1. class Simple{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(ArithmeticException e){System.out.println(e);}
8.
9. finally{System.out.println("finally block is always executed");}
10.
11. System.out.println("rest of the code...");
12. }
13. }
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...
Rule: For each try block there can be zero or more catch blocks, but only one finally block.
Note: The finally block will not be executed if program exits(either by calling System.exit() or by
causing a fatal error that causes the process to abort).
throw keyword
So far, you have only been catching exceptions that are thrown by the Java run-time system. However, it is possible for
your program to throw an exception explicitly, using the throw statement. The general form of throw is shown here:
throw ThrowableInstance;
Page 9 of 13
Here,ThrowableInstance must be an object of type Throwable or a subclass of Throwable. Simple types, such as int or
char, as well as non-Throwableclasses, such as String and Object, cannot be used as exceptions. There are two ways you
can obtain
A Throwableobject: using a parameter into a catch clause, or creating one with the new operator.
The throw keyword is used to explicitly throw an exception. We can throw either checked or uncheked exception. The
throw keyword is mainly used to throw custom exception. We will see custom exceptions later.
Example of throw keyword
In this example, we have created the validate method that takes integer value as a parameter. If the age is less than 18,
we are throwing the ArithmeticException otherwise print a message welcome to vote.
1. class Excep13{
2. static void validate(int age){
3. if(age<18)
4. throw new ArithmeticException("not valid");
5. else
6. System.out.println("welcome to vote");
7. }
8.
9. public static void main(String args[]){
10. validate(13);
11. System.out.println("rest of the code...");
12. }
13. }
Output:Exception in thread main java.lang.ArithmeticException:not valid
Exception propagation:
An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous
method,If not caught there, the exception again drops down to the previous method, and so on until they are caught or
until they reach the very bottom of the call stack.This is called exception propagation.
Rule: By default Unchecked Exceptions are forwarded in calling chain (propagated).
Program of Exception Propagation
1. class Simple{
2. void m(){
3. int data=50/0;
4. }
5. void n(){
6. m();
7. } // Class Simple ends
8.
9. void p(){
10. try{
11. n();
12. }catch(Exception e){System.out.println("exception handled");}
13. }
14. public static void main(String args[]){
15. Simple obj=new Simple();
Page 10 of 13
16. obj.p();
17. System.out.println("normal flow...");
18. }
19. }
Output:exception handled
normal flow...
In the above example exception occurs in m() method where it is not handled,so it is propagated to previous n() method
where it is not handled, again it is propagated to p() method where exception is handled.
Exception can be handled in any method in call stack either in main() method,p() method,n() method or m() method.
The flow of execution stops immediately after the throw statement; any subsequent statements are not executed. The
nearest enclosing try block is inspected to see if it has a catch statement that matches the type of the exception. If it
does find a match, control is transferred to that statement. If not, then the next enclosing try statement is inspected,
and so on. If no matching catch is found, then the default exception handler halts the program and prints the stack
trace.
Here is a sample program that creates and throws an exception. The handler that catches the exception rethrows it to
the outer handler.
// Demonstrate throw.
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}
This program gets two chances to deal with the same error. First,main( )sets up an exception context and then calls
demoproc( ). The demoproc( )method then sets up another exception-handling context and immediately throws a new
instance of NullPointerException,which is caught on the next line. The exception is then rethrown. Here is the resulting
output:
Page 11 of 13
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo
The program also illustrates how to create one of Java’s standard exception objects.
Pay close attention to this line:
throw new NullPointerException("demo");
Here,new is used to construct an instance of NullPointerException. All of Java’s built-in run-time exceptions have at least
two constructors: one with no parameter and one that takes a string parameter. When the second form is used, the
argument specifies a string that describes the exception. This string is displayed when the object is used as an argument
toprint( ) or println( ). It can also be obtained by a call to getMessage( ), which is defined byThrowable.
throws keyword:
If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the
method can guard themselves against that exception. You do this by including a throws clause in the method’s
declaration. A throws clause lists the types of exceptions that a method might throw. This is necessary for all exceptions,
except those of type Error or RuntimeException, or any of their subclasses. All other exceptions that a method can throw
must be declared in thethrowsclause. If they are not, a compile-time error will result.
This is the general form of a method declaration that includes a throws clause:
type method-name(parameter-list)throwsexception-list
{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a method can throw.
The throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an
exception so it is better for the programmer to provide the exception handling code so that normal flow can be
maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as
NullPointerException, it is programmers fault that he is not performing check up before the code being used.
Following is an example of an incorrect program that tries to throw an exception that it does not catch. Because the
program does not specify a throws clause to declare this fact, the program will not compile.
// This program contains an error and will not compile.
class ThrowsDemo {
static void throwOne() {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
throwOne();
}
}
To make this example compile, you need to make two changes.
 First, you need to declare that throwOne()throwsIllegalAccessException.
 Second,main( )must define a try/catch statement that catches this exception.
Page 12 of 13
The corrected example is shown here:
// This is now correct.
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
Here is the output generated by running this example program:
inside throwOne
caught java.lang.IllegalAccessException: demo
Difference between throw and throws:
1)throw is used to explicitly throw an exception. throws is used to declare an exception.
2)checked exception can not be propagated without throws. checked exception can be propagated with throws.
3)throw is followed by an instance. throws is followed by class.
4)throw is used within the method. throws is used with the method signature.
5)You cannot throw multiple exception You can declare multiple exception e.g.
public void method()throws IOException,SQLException.
Custom Exception :
If you are creating your own Exception that is known as custom exception or user-defined exception.
1. //Example of custom exception
2.
3. class InvalidAgeException extends Exception{
4. InvalidAgeException(String s){
5. super(s);
6. }
7. }
8. class Excep13{
9.
10. static void validate(int age)throws InvalidAgeException{
11. if(age<18)
12. throw new InvalidAgeException("not valid");
13. else
14. System.out.println("welcome to vote");
15. }
16.
17. public static void main(String args[]){
18. try{
19. validate(13);
20. }catch(Exception m){System.out.println("Exception occured: "+m);}
21.
Page 13 of 13
22. System.out.println("rest of the code...");
23. }
24. }
Output:Exception occured: InvalidAgeException:not valid
rest of the code...
Unchecked Exceptions
Those exceptions, that need not be included in any method’s throws list are called unchecked exceptions because the
compiler does not check to see if a method handles or throws these exceptions.
Examples:
Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread.
IllegalStateException Environment or application is in incorrect state.
IllegalThreadStateException Requested operation not compatible with current thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
and more….
Checked Exceptions
Those exceptions defined in java.lang that must be included in a method’s throws list if that method can generate one of
these exceptions and does not handle it itself.
Examples:
Exception Meaning
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object that does not implement theCloneableinterface.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class or interface.
InterruptedException One thread has been interrupted byanother thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.

Class notes(week 8) on exception handling

  • 1.
    Page 1 of13 Class Notes on Exception handling (Week - 8) Contents: - Exception handling basics, different types of exception classes, use of try & catch with throw, throws & finally, creation of user defined exception classes. Exception Handling in Java The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the runtime errors so that normal flow of the application can be maintained. In this Note, we will know about exception, its type and the difference between checked and unchecked exceptions. Exception  Dictionary Meaning:Exception is an abnormal condition.  In java, exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime. An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following:  A user has entered invalid data.  A file that needs to be opened cannot be found.  A network connection has been lost in the middle of communications, or the JVM has run out of memory. Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner. To understand how exception handling works in Java, you need to understand the three categories of exceptions:  Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation. The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.  Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation. The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile- time rather they are checked at runtime.  Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation. Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc. Exception Handling Exception Handling is a mechanism to handle runtime errors.
  • 2.
    Page 2 of13 Advantage of Exception Handling The core advantage of exception handling is that normal flow of the application is maintained. Exception normally disrupts the normal flow of the application that is why we use exception handling. Let's take a scenario: 1. statement 1; 2. statement 2; 3. statement 3; 4. statement 4; 5. statement 5; 6. statement 6; 7. statement 7; 8. statement 8; 9. statement 9; Suppose there is 9 statements in your program and there occurs an exception at statement 5, rest of the code will not be excecuted i.e. statement 6 to 9 will not run. If we perform exception handling, rest of the exception will be executed. That is why we use exception handling. Common scenarios of Exception Handling where exceptions may occur There are given some scenarios where unchecked exceptions can occur. They are as follows: 1) Scenario where ArithmeticException occurs If we divide any number by zero, there occurs an ArithmeticException. 1. int a=50/0; // ArithmeticException 2) Scenario where NullPointerException occurs If we have null value in any variable, performing any operation by the variable occurs an NullPointerException. 1. String s=null; 2. System.out.println(s.length()); // NullPointerException 3) Scenario where NumberFormatException occurs The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable that have characters, converting this variable into digit will occur NumberFormatException. 1. String s="abc"; 2. int i=Integer.parseInt(s); // NumberFormatException 4) Scenario where ArrayIndexOutOfBoundsException occurs If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown below: 1. int a[]=new int[5]; 2. a[10]=50; // ArrayIndexOutOfBoundsException
  • 3.
    Page 3 of13 Use of try-catch block in Exception handling: Five keywords used in Exception handling: 1. try 2. catch 3. finally 4. throw 5. throws try block Enclose the code that might throw an exception in try block. It must be used within the method and must be followed by either catch or finally block. Syntax of try with catch block 1. try{ 2. ... 3. }catch(Exception_class_Name reference_variable_or_object){ … } Syntax of try with finally block 1. try{ 2. ... 3. }finally{} catch block Catch block is used to handle the Exception. It must be used after the try block. Problem without exception handling 1. class Simple{ 2. public static void main(String args[]){ 3. int data=50/0; 4. 5. System.out.println("rest of the code..."); 6. } 7. } Output:Exception in thread main java.lang.ArithmeticException:/ by zero As displayed in the above example, rest of the code is not executed i.e. rest of the code... statement is not printed. Let's see what happens behind the scene:
  • 4.
    Page 4 of13 What happens behind the code int a=50/0; The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM provides a default exception handler that performs the following tasks:  Prints out exception description.  Prints the stack trace (Hierarchy of methods where the exception occurred).  Causes the program to terminate. But if exception is handled by the application programmer, normal flow of the application is maintained i.e. rest of the code is executed. Solution by exception handling 1. class Simple{ 2. public static void main(String args[]){ 3. try{ 4. int data=50/0; 5. 6. }catch(ArithmeticException e){System.out.println(e);} 7. 8. System.out.println("rest of the code..."); 9. } // main ends 10. } // class ends Output:Exception in thread main java.lang.ArithmeticException:/ by zero rest of the code... Now, as displayed in the above example, rest of the code is executed i.e. rest of the code... statement is printed. Multiple catch block If you have to perform different tasks at the occrence of different Exceptions, use multple catch block.
  • 5.
    Page 5 of13 Rule 1: At a time only one Exception is occured and at a time only one catch block is executed. Rule 2: All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come before catch for Exception class Excep4{ public static void main(String args[]){ try{ int a[]=new int[5]; a[5]=30/0; } catch(Exception e){System.out.println("common task completed");} catch(ArithmeticException e){System.out.println("task1 is completed");} catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");} System.out.println("rest of the code..."); } } Output: (Compile time Error) Excep4.java:8: exception java.lang.ArithmeticException has already been caught catch(ArithmeticException e){System.out.println("task1 is completed");} ^ Excep4.java:9: exception java.lang.ArrayIndexOutOfBoundsException has already been caught catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed"); } ^ 2 errors Explanation If you try to compile this program, you will receive an error message stating that the second and third catch statement is unreachable(look at the error messages) because the exception has already been caught. Since ArithmeticExceptionis a subclass of Exception, the first catch statement will handle all Exception-based errors, including ArithmeticException. This means that the second and third catch statement will never execute. To fix the problem, reverse the order of the catch statements or just put the catch(Exception e) statement at last. Modified Program class Excep4{ public static void main(String args[]){ try{ int a[]=new int[5]; //a[10]=90; if we uncomment this line then ArrayIndexOutOfBoundsException a[5]=30/0; // generates ArithmeticException } catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");} catch(ArithmeticException e){System.out.println("task1 is completed");} catch(Exception e){System.out.println("common task completed");} System.out.println("rest of the code..."); } } Output: task1 is completed rest of the code...
  • 6.
    Page 6 of13 Nested try block: try block within a try block is known as nested try block. Why use nested try block? Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested Syntax: 1. .... 2. try 3. { 4. statement 1; 5. statement 2; 6. try 7. { 8. statement 1; 9. statement 2; 10. } 11. catch(Exception e) 12. { 13. } 14. } 15. catch(Exception e) 16. { 17. } 18. .... Example of nested try block class Excep6{ public static void main(String args[]){ try{ try{ System.out.println("going to divide"); int b =39/0; }catch(ArithmeticException e){System.out.println(e);} try{ int a[]=new int[5]; // int x=7/0; uncomment,then catch(Exception e) handled a[5]=4; }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);} System.out.println("other statement”); }catch(Exception e){System.out.println("All Exceptions handeled");} System.out.println("normal flow.."); } } OUTPUT: going to divide java.lang.ArithmeticException: / by zero java.lang.ArrayIndexOutOfBoundsException: 5
  • 7.
    Page 7 of13 other statement normal flow.. finally block The finally block is a block that is always executed. It is mainly used to perform some important tasks such as closing connection, stream etc. Note:Before terminating the program, JVM executes finally block(if any). Note:finally must be followed by try or catch block. Why use finally block?  finally block can be used to put "cleanup" code such as closing a file,closing connection etc. case 1 Program in case exception does not occur 1. class Simple{ 2. public static void main(String args[]){ 3. try{ 4. int data=25/5; 5. System.out.println(data); 6. } 7. catch(NullPointerException e){System.out.println(e);} 8. 9. finally{System.out.println("finally block is always executed");} 10. 11. System.out.println("rest of the code..."); 12. } 13. } Output:5 finally block is always executed rest of the code...
  • 8.
    Page 8 of13 case 2 Program in case exception occured but not handled 1. class Simple{ 2. public static void main(String args[]){ 3. try{ 4. int data=25/0; 5. System.out.println(data); 6. } 7. catch(NullPointerException e){System.out.println(e);} 8. 9. finally{System.out.println("finally block is always executed");} 10. 11. System.out.println("rest of the code..."); 12. } 13. } Output:finally block is always executed Exception in thread main java.lang.ArithmeticException:/ by zero case 3 Program in case exception occured and handled 1. class Simple{ 2. public static void main(String args[]){ 3. try{ 4. int data=25/0; 5. System.out.println(data); 6. } 7. catch(ArithmeticException e){System.out.println(e);} 8. 9. finally{System.out.println("finally block is always executed");} 10. 11. System.out.println("rest of the code..."); 12. } 13. } Output:Exception in thread main java.lang.ArithmeticException:/ by zero finally block is always executed rest of the code... Rule: For each try block there can be zero or more catch blocks, but only one finally block. Note: The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort). throw keyword So far, you have only been catching exceptions that are thrown by the Java run-time system. However, it is possible for your program to throw an exception explicitly, using the throw statement. The general form of throw is shown here: throw ThrowableInstance;
  • 9.
    Page 9 of13 Here,ThrowableInstance must be an object of type Throwable or a subclass of Throwable. Simple types, such as int or char, as well as non-Throwableclasses, such as String and Object, cannot be used as exceptions. There are two ways you can obtain A Throwableobject: using a parameter into a catch clause, or creating one with the new operator. The throw keyword is used to explicitly throw an exception. We can throw either checked or uncheked exception. The throw keyword is mainly used to throw custom exception. We will see custom exceptions later. Example of throw keyword In this example, we have created the validate method that takes integer value as a parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote. 1. class Excep13{ 2. static void validate(int age){ 3. if(age<18) 4. throw new ArithmeticException("not valid"); 5. else 6. System.out.println("welcome to vote"); 7. } 8. 9. public static void main(String args[]){ 10. validate(13); 11. System.out.println("rest of the code..."); 12. } 13. } Output:Exception in thread main java.lang.ArithmeticException:not valid Exception propagation: An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method,If not caught there, the exception again drops down to the previous method, and so on until they are caught or until they reach the very bottom of the call stack.This is called exception propagation. Rule: By default Unchecked Exceptions are forwarded in calling chain (propagated). Program of Exception Propagation 1. class Simple{ 2. void m(){ 3. int data=50/0; 4. } 5. void n(){ 6. m(); 7. } // Class Simple ends 8. 9. void p(){ 10. try{ 11. n(); 12. }catch(Exception e){System.out.println("exception handled");} 13. } 14. public static void main(String args[]){ 15. Simple obj=new Simple();
  • 10.
    Page 10 of13 16. obj.p(); 17. System.out.println("normal flow..."); 18. } 19. } Output:exception handled normal flow... In the above example exception occurs in m() method where it is not handled,so it is propagated to previous n() method where it is not handled, again it is propagated to p() method where exception is handled. Exception can be handled in any method in call stack either in main() method,p() method,n() method or m() method. The flow of execution stops immediately after the throw statement; any subsequent statements are not executed. The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of the exception. If it does find a match, control is transferred to that statement. If not, then the next enclosing try statement is inspected, and so on. If no matching catch is found, then the default exception handler halts the program and prints the stack trace. Here is a sample program that creates and throws an exception. The handler that catches the exception rethrows it to the outer handler. // Demonstrate throw. class ThrowDemo { static void demoproc() { try { throw new NullPointerException("demo"); } catch(NullPointerException e) { System.out.println("Caught inside demoproc."); throw e; // rethrow the exception } } public static void main(String args[]) { try { demoproc(); } catch(NullPointerException e) { System.out.println("Recaught: " + e); } } } This program gets two chances to deal with the same error. First,main( )sets up an exception context and then calls demoproc( ). The demoproc( )method then sets up another exception-handling context and immediately throws a new instance of NullPointerException,which is caught on the next line. The exception is then rethrown. Here is the resulting output:
  • 11.
    Page 11 of13 Caught inside demoproc. Recaught: java.lang.NullPointerException: demo The program also illustrates how to create one of Java’s standard exception objects. Pay close attention to this line: throw new NullPointerException("demo"); Here,new is used to construct an instance of NullPointerException. All of Java’s built-in run-time exceptions have at least two constructors: one with no parameter and one that takes a string parameter. When the second form is used, the argument specifies a string that describes the exception. This string is displayed when the object is used as an argument toprint( ) or println( ). It can also be obtained by a call to getMessage( ), which is defined byThrowable. throws keyword: If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. You do this by including a throws clause in the method’s declaration. A throws clause lists the types of exceptions that a method might throw. This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses. All other exceptions that a method can throw must be declared in thethrowsclause. If they are not, a compile-time error will result. This is the general form of a method declaration that includes a throws clause: type method-name(parameter-list)throwsexception-list { // body of method } Here, exception-list is a comma-separated list of the exceptions that a method can throw. The throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained. Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers fault that he is not performing check up before the code being used. Following is an example of an incorrect program that tries to throw an exception that it does not catch. Because the program does not specify a throws clause to declare this fact, the program will not compile. // This program contains an error and will not compile. class ThrowsDemo { static void throwOne() { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[]) { throwOne(); } } To make this example compile, you need to make two changes.  First, you need to declare that throwOne()throwsIllegalAccessException.  Second,main( )must define a try/catch statement that catches this exception.
  • 12.
    Page 12 of13 The corrected example is shown here: // This is now correct. class ThrowsDemo { static void throwOne() throws IllegalAccessException { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[]) { try { throwOne(); } catch (IllegalAccessException e) { System.out.println("Caught " + e); } } } Here is the output generated by running this example program: inside throwOne caught java.lang.IllegalAccessException: demo Difference between throw and throws: 1)throw is used to explicitly throw an exception. throws is used to declare an exception. 2)checked exception can not be propagated without throws. checked exception can be propagated with throws. 3)throw is followed by an instance. throws is followed by class. 4)throw is used within the method. throws is used with the method signature. 5)You cannot throw multiple exception You can declare multiple exception e.g. public void method()throws IOException,SQLException. Custom Exception : If you are creating your own Exception that is known as custom exception or user-defined exception. 1. //Example of custom exception 2. 3. class InvalidAgeException extends Exception{ 4. InvalidAgeException(String s){ 5. super(s); 6. } 7. } 8. class Excep13{ 9. 10. static void validate(int age)throws InvalidAgeException{ 11. if(age<18) 12. throw new InvalidAgeException("not valid"); 13. else 14. System.out.println("welcome to vote"); 15. } 16. 17. public static void main(String args[]){ 18. try{ 19. validate(13); 20. }catch(Exception m){System.out.println("Exception occured: "+m);} 21.
  • 13.
    Page 13 of13 22. System.out.println("rest of the code..."); 23. } 24. } Output:Exception occured: InvalidAgeException:not valid rest of the code... Unchecked Exceptions Those exceptions, that need not be included in any method’s throws list are called unchecked exceptions because the compiler does not check to see if a method handles or throws these exceptions. Examples: Exception Meaning ArithmeticException Arithmetic error, such as divide-by-zero. ArrayIndexOutOfBoundsException Array index is out-of-bounds. ArrayStoreException Assignment to an array element of an incompatible type. ClassCastException Invalid cast. IllegalArgumentException Illegal argument used to invoke a method. IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread. IllegalStateException Environment or application is in incorrect state. IllegalThreadStateException Requested operation not compatible with current thread state. IndexOutOfBoundsException Some type of index is out-of-bounds. NegativeArraySizeException Array created with a negative size. and more…. Checked Exceptions Those exceptions defined in java.lang that must be included in a method’s throws list if that method can generate one of these exceptions and does not handle it itself. Examples: Exception Meaning ClassNotFoundException Class not found. CloneNotSupportedException Attempt to clone an object that does not implement theCloneableinterface. IllegalAccessException Access to a class is denied. InstantiationException Attempt to create an object of an abstract class or interface. InterruptedException One thread has been interrupted byanother thread. NoSuchFieldException A requested field does not exist. NoSuchMethodException A requested method does not exist.