Chapter Four
Chapter Four
Chapter-Four
Exception Handling
Compiled By Minichil A.
1
Exception Handling
The exception handling in java is one of the powerful mechanism to handle the
An Exception is an unwanted event that interrupts the normal flow of the program
When an exception occurs program execution gets terminated. In such cases we get a system generated
error message
The good thing about exceptions is that they can be handled in Java
By handling the exceptions we can provide a meaningful message to the user about the issue rather than a
Exception handling ensures that the flow of the program doesn’t break when an
exception occurs
Exception normally disrupts the normal flow of the application that is
1. Checked exceptions
2. Unchecked exceptions
3
Cont..
Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks
them during compilation to see whether the programmer has handled them or not.
If these exceptions are not handled/declared in the program, you will get compilation error
Unchecked Exceptions
These exceptions are not checked at compile time so compiler does not check whether the programmer
5
Cont..
Common Scenarios of Java Exceptions
There are given some scenarios where unchecked exceptions may occur. They are as follows
int a = 12 / 0; // ArithmeticException
NullPointerException
String s = null;
System.out.println(length); NullPointerException
6
Cont..
A scenario where NumberFormatException Occurs
If the formatting of any variable or number is mismatched. It may result into NumberFormatException
Suppose we have a string variable that has characters, converting this variable into digit will cause
NumberFormatException
String s = “abc”;
int i = integer.parseint(s); // NumberFormatException
7
Try Catch in Java – Exception handling
Try block
The try block contains set of statements where an exception can occur.
A try block is always followed by a catch block, which handles the exception that occurs in associated try
block
A try block must be followed by catch blocks or finally block or both
Syntax of try block
try{
//statements that may cause an exception
}
While writing a program, if you think that certain statements in a program can throw an exception,
A single try block can have several catch blocks associated with it.
When an exception occurs in try block, the corresponding catch block that handles that particular exception executes
try
{
//statements that may cause an exception
}
catch (exception(type) e(object
{
//error handling code
9
}
Example: try catch block
If an exception occurs in try block then the control of execution is passed to the corresponding catch
block
A single try block can have multiple catch blocks associated with it
catch (ArithmeticException e) {
class Example1 { /* This block will only execute if any Arithmetic
public static void main(String args[]) { exception
int num1, num2; * occurs in try block
try { */
/* We suspect that this block of statement can System.out.println("You should not divide a
throw number by zero");
* exception so we handled it by placing these }
catch (Exception e) {
statements
/* This is a generic Exception handler which means
* inside try and handled the exception in it can handle
catch block * all the exceptions. This will execute if the
*/ exception is not
num1 = 0; * handled by previous catch blocks.
num2 = 62 / num1; */
System.out.println(num2); System.out.println("Exception occurred");
System.out.println("Hey I'm at the end of try }
System.out.println("I'm out of try-catch block in
10 block");}
Java.");}}
Multiple catch blocks in Java
The example we seen above is having multiple catch blocks, lets see few rules about multiple catch
blocks
2. A generic catch block can handle all the exceptions, Whether it is ArrayIndexOutOfBoundsException
or ArithmeticException or NullPointerException or any other type of exception, this handles all of
them
catch(Exception e){
//This catch block catches all the exceptions
}
3. If no exception occurs in try block then the catch blocks are completely ignored.
4. Corresponding catch blocks execute for that specific type of exception:
11
5. You can also throw exception,
Catching multiple exceptions
class Example{
public static void main(String args[]){
try{
int arr[]=new int[7];
arr[4]=30/0;
In the following example, the first catch block got executed because System.out.println("Last Statement of try block");
the code we have written in try block throws ArithmeticException }
(because we divided the number by zero). catch(ArithmeticException e){
System.out.println("You should not divide a
number by zero");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Accessing array elements
outside of the limit");
}
catch(Exception e){
System.out.println("Some Other Exception");
}
Output: System.out.println("Out of the try-catch block");
You should not divide a number by zero }
12 Out of the try-catch block }
Now lets change the code a little bit and see the change in output:
In this case, the second catch block got executed because the code class Example{
public static void main(String args[]){
throws ArrayIndexOutOfBoundsException. We are trying to access the try{
11th element of array in above program but the array size is only 7. int arr[]=new int[7];
arr[10]=10/5;
System.out.println("Last Statement of try block");
}
catch(ArithmeticException e){
System.out.println("You should not divide a
number by zero");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Accessing array elements
outside of the limit");
}
catch(Exception e){
System.out.println("Some Other Exception");
}
Output: System.out.println("Out of the try-catch block");
Accessing array elements outside of the limit }
Out of the try-catch block }
13
Java Finally block – Exception handling
A finally block contains all the crucial statements that must be executed whether exception occurs or not.
The statements present in this block will always execute regardless of whether exception occurs in try
A finally block must be associated with a try block, you cannot use finally without a try block. You
should place those statements in this block that must be executed always
Finally block is optional, as we have seen in previous examples that a try-catch block is sufficient for
exception handling, however if you place a finally block then it will always run after the execution of
try block.
In normal case when there is no exception in try block then the finally block is executed after try
block. However if an exception occurs then the catch block is executed before finally block
An exception in the finally block, behaves exactly like any other exception
The statements present in the finally block execute even if the try block contains control transfer
15
Another example of finally block and return statement
You can see that even though we have return statement in the method, the finally block
still runs.
class JavaFinally
{
public static void main(String args[])
{
System.out.println(JavaFinally.myMethod());
}
public static int myMethod()
{ Output:
try { This is Finally block
return 112; Finally block run even after return statement
} 112
finally {
System.out.println("This is Finally block");
System.out.println("Finally block run even
after return statement");
}
}
16 }
Java throw keyword
The Java throw keyword is used to explicitly throw an exception
We can define our own set of conditions or rules and throw an exception explicitly using
throw keyword.
Syntax of throw keyword:
NullPointerException etc.
These exceptions are already set to trigger on pre-defined conditions such as when you
keyword
These exceptions are known as user-defined or custom exceptions
19
Example of User defined exception in Java
/* This is my Exception class, I have named it MyException class Example1{
* you can give any name, just remember that it should public static void main(String args[]){
* extend Exception class try{
*/ System.out.println("Starting of try block");
class MyException extends Exception{ // I'm throwing the custom exception using throw
String str1; throw new MyException("This is My error
/* Constructor of custom exception class Message");
* here I am copying the message that we are passing while }
* throwing the exception to a string and then displaying catch(MyException exp){
* that string along with the message. System.out.println("Catch Block") ;
*/ System.out.println(exp) ;
MyException(String str2) { }
str1=str2; }
} }
public String toString(){
return ("MyException Occurred: "+str1) ; Output:
} Starting of try block
} Catch Block
MyException Occurred: This is My error Message
20
Thank
You!!
21