0% found this document useful (0 votes)
30 views24 pages

Exception Handling

Uploaded by

shresthasudip574
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views24 pages

Exception Handling

Uploaded by

shresthasudip574
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

EXCEPTION HANDLING

EXCEPTION
The unwanted, unexpected activities which disturbs the normal flow of the program is
known as exception. In Java, an exception is an event that disrupts the normal flow of
the program.

The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that the normal flow of the application can be maintained.

class ExceptionExample
{
public static void main(String args[]){
sum();
}
public static void sum(){
mul();
}
public static void mul(){
System.out.println("Hello World");
}
}

Note: If I put some exception type code anywhere, exception arise and if the
handling code doesn’t provide by the caller method then JVM destroys the caller
methods and hand over this code to the default Exception handler which does
nothings. It just prints the exception.

class ExceptionExample
{
public static void main(String args[]){
sum();
}
public static void sum(){
mul();
}
public static void mul(){
System.out.println(10/0);
}

1
}
Hierarchy of Java Exception classes
The java.lang.Throwable class is the root class of Java Exception hierarchy. It is
inherited by two subclasses: Exception and Error. The hierarchy of Java Exception
classes is given below:

The exception which is recoverable by the programmer is called Exception.


The exception which cannot be recoverable by the programmer is called
Error. It is created due to lack of system specification

Types of Java Exception


Checked Exception
Unchecked Exception

2
The most important Question of java Exception
What is checked and unchecked Exception?
The exception which is checked at the compile time by the compiler for the smooth
running of the program at run time is known as checked exception.

The exception which is checked at the run time is known as unchecked exception.

Note: All the runtime exception and the errors are by default unchecked exception
and the rest of all are checked exception.

Fully checked and Partially checked Exception


The exception whose child class are checked is known as fully checked exception and
the exception who’s some of the child class are checked and some of the child class are
unchecked those exception is partially checked exception.

Java Exception Keywords


Java provides five keywords that are used to handle the exception. The following table
describes each.

3
Without try catch block
class test
{
public static void main(String args[])
{
System.out.println("Statement 1");
System.out.println(10/0);
System.out.println("Statement 2");
System.out.println("Statement 3");
}
}
With try catch block
class Test1
{
public static void main(String args[])
{
System.out.println("Statement 1");
try
{
System.out.println(10/0);
}
catch(ArithmeticException e)
{
System.out.println(10/2);
}
System.out.println("Statement 2");
System.out.println("Statement 3");
}
}

Hence we should only keep the risky code in the try block

4
Control Flow inside Try catch block
try
{
statement 1;
statement 2;
statement 3;
}
catch(ArithmeticException e)
{
statement 4;
}
statement 5;

1. If there is no exception.

2. If an exception raised at statement 2 and corresponding catch block matched.

3. If an exception raised at statement 2 and corresponding catch block not matched

Way to print the exception


There are three ways to print the exception

1. printStackTrace() (Name of Exception, Description and Stack trace)


2. toString() or e (Name of Exception, Description)
3. getMessage() ( Only Description)

public class PrintExceptionMessage1


{
public static void divide()
{
try
{
int a = 100/0;
}
catch (Exception e)
{
System.out.println(e);
}
}

5
public static void main(String args[])
{
divide();
}
}
Output

public class PrintExceptionMessage1


{
public static void divide()
{
try
{
int a = 100/0;
}
catch (Exception e)
{
e.printStackTrace();
}
public static void main(String args[])
{
divide();
}
}
Output

System.out.println(e.getMessage());

System.out.println(e.toString()); // same as System.out.println(e);

6
Try with multiple catch block
Trytry Try
{ { {
10/0;
10/0; 10/0;
} } }
catch(ArithmeticException
catch(Exception e) e){ catch(ArithmeticException e)
{ } {
} catch(Exception e){ }
}
catch(ArithmeticException e) catch(Exception e)
{ {
} }

If there is a multiple catch block available, order of the Exception must be


followed. i.e. parent exception must be the first exception catch block

public class MultipleCatchBlock2 {

public static void main(String[] args) {

try{
int a[]=new int[5];

System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{

7
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
public class MultipleCatchBlock3 {

public static void main(String[] args) {


try{
int a[]=new int[5];
a[5]=30/0;
System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
class MultipleCatchBlock5{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}

8
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...");
}
}
Common Scenarios of Java Exceptions
1) A scenario where ArithmeticException occurs

 If we divide any number by zero, there occurs an ArithmeticException.

int a=50/0; //ArithmeticException

2) A scenario where NullPointerException occurs

 If we have a null value in any variable, performing any operation on the variable
throws a NullPointerException.

String s=null;

System.out.println(s.length()); //NullPointerException

3) 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

4) A scenario where ArrayIndexOutOfBoundsException occurs

9
 When an array exceeds to its size, the ArrayIndexOutOfBoundsException
occurs. there may be other reasons to occur
ArrayIndexOutOfBoundsException.

Consider the following statements.

int a[]=new int[5];

a[10]=50; //ArrayIndexOutOfBoundsException

Internal Working of Java try-catch block

1. 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).

10
Causes the program to terminate.
2. But if the application programmer handles the exception, the normal flow of the
application is maintained, i.e., rest of the code is executed.

Java Nested try block


In Java, using a try block inside another try block is permitted. It is called as nested try
block. Every statement that we enter a statement in try block, context of that exception
is pushed onto the stack.

Syntax
try
{
statement 1;
statement 2;
try
{
statement 3;
statement 4;
try
{
statement 5;
statement 6;
}
catch(Exception e2)
{
}
}
catch(Exception e1)
{
}
}
catch(Exception e3)
{
}

11
Example

public class NestedTryBlock{


public static void main(String args[]){
try{
try{
System.out.println("going to divide by 0");
int b =39/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}

try{
int a[]=new int[5];
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement");
}
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}
}

12
Example 2
public class NestedTryBlock2 {
public static void main(String args[])
{
try {
try {
try {
int arr[] = { 1, 2, 3, 4 };
System.out.println(arr[10]);
}
catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println(" inner try block 2");
}
}
catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println("inner try block 1");
}
}
catch (ArrayIndexOutOfBoundsException e4) {
System.out.print(e4);
System.out.println(" outer (main) try block");
}
}
}

Java finally block


Java finally block is a block used to execute important code such as closing the
connection, etc.

Java finally block is always executed whether an exception is handled or not. Therefore,
it contains all the necessary statements that need to be printed regardless of the
exception occurs or not.

13
The finally block follows the try-catch block.

Why use Java finally block?


finally block in Java can be used to for "cleanup" the code such as closing a file,
closing connection, etc.
The important statements to be printed can be placed in the finally block.

Note: If you don't handle the exception, before terminating the program, JVM
executes finally block (if any).

Flowchart

Case 1: When an exception does not occur


class TestFinallyBlock {
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);

14
}
catch(NullPointerException e){
System.out.println(e);
}
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}

Case 2: When an exception occur but not handled by the catch block

public class TestFinallyBlock1{


public static void main(String args[]){
try {
System.out.println("Inside the try block");
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){
System.out.println(e);
}
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}

Case 3: you do by yourself

Rule: For each try block there can be zero or more catch blocks, but only one finally
block.

15
Note: The finally block will not be executed if the program exits (either by calling
System.exit() or by causing a fatal error that causes the process to abort).

Java throw Keyword


The Java throw keyword is used to throw an exception explicitly to the JVM.

We can throw either checked or unchecked exceptions in Java by throw keyword. It is


mainly used to throw a customize exception.

Customize exception means the exception created by the programmer. User defined
exception.

It is highly recommended to use throw keyword for unchecked exception.

throw new exception_class("error message");

throw new IOException("sorry device error");

public class TestThrow1 {


public void validate(int age) {
if(age<18) {
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
public static void main(String args[]){
TestThrow1 t=new TestThrow1();
t.validate(13);
System.out.println("rest of the code...");
}
}

16
class Test10{ Exception object created and hand
public static void main(String args[]{ Over this Exception object to the
JVM Internally
System.out.println(10/0);

class Test10{

public static void main(String args[]{


Exception object created and hand
throw new ArithmeticException("/Zero"); Over this Exception object to the
} JVM Manually

class Test10{

public static void main(String args[]{

System.out.println(10/0);

System.out.println("Hello");

class Test10{

public static void main(String args[]{

throw new ArithmeticException("/Zero");

System.out.println("Hello");

In the first class the code will easily compile but for the second class the code does
not compile.

class Test10{
17
static ArithmeticException e= new ArithmeticException();

public static void main(String args[]{


In first class ArithmeticException will be thrown but in the next code the
NullPointerException will be thrown.

Customized Throw Exception


Make your own class and extends Throwable class and throw this.

Throw inside try catch block


class Division {
public static void main(String[] args)
{
int a = 10, b = 5, c = 5, result;
try {
result = a / (b - c);
//throw new Exception("default error");
System.out.println("result" + result);
}

catch (Exception e) {
System.out.println("Exception caught:Division by zero");

18
System.out.println(e);
}

finally {
System.out.println("I am in final block");
}
}
}
Another Example
class Test11{
public static void main(String args[])
{
throw new Exception(); // CE because of checked Exception
throw new Error(); // CE because of unchecked Exception
}
}

throws Keyword in Java


If there may be the chance of occurring the exception in the java code, then this
exception can be handle by two ways.

 Using Try catch block


 Using throws keyword

throws Keyword
To delegate the responsibility of the exception handling to the caller we use throws
keyword.

 We can handle only checked exception by using throws keyword.


 It is highly recommended to use throws keyword for checked exception.

class Test{ class Test{

public static void main(String args[]){ public static void main(String args[]) throws Exception

Thread.sleep(1000); {

} Thread.sleep(1000);
Which approach is recommended and which one is not recommended?
} }
19
}
If really a checked exception occurs and when we use throws keyword to handle the
exception, throws keyword delegate it to JVM and JVM is responsible to handle the
exception.

If JVM handles the exception, it means program terminates abnormally. So, throws
keyword is not at all recommended over try catch block.

throws keyword in multiple methods


class ExceptionExample1
{
public static void main(String args[]) throws Exception
{
sum();
}
public static void sum() throws Exception
{
mul();
}
public static void mul() throws InterruptedException
{
Thread.sleep(1000);
}
}

Different important cases of Exception

1 2
try try
{ {
System.out.println("Hello"); System.out.println("Hello");
} }
catch(ArithmeticException e) catch(Exception e)
{ {
} }

3 4
try try
{ {
20 System.out.println("Hello");
System.out.println("Hello");
} }
catch(InterruptedException e) catch(IOException e)
{
5
try
{
System.out.println("Hello");
}
catch(Error e)
{
}

1, 2 and 5 are perfectly correct, perfectly works.

But the remaining 3 and 4 gives compile time Error. (fully checked)

Rule: within the try block if there is no chance of rising any exception you can’t
write the catch block but this rule is applicable only for fully checked exception.

Difference between throw and throws keyword

21
Difference between Final, finally, Finalize.
final
final is keyword which is used only for

1. class
2. method
3. variable

If we declare a class as a final, we can’t extend the class it means inheritance is not
possible.

If we declare a method as a final, we can’t override the method in the child class it
means overridden in not possible

If we declare a variable as a final, we can’t change the value of that variable it means the
variable becomes constant.

finally

22
finally, is a block associated with try catch. The main purpose of finally block is to
maintain cleanup code. The specialty of the finally block is, it will always execute
weather the exception occurs or not.

try
{
//Risky code
}
catch ()
{
//Handling code
}
finally
{
//Clean up code, resources deallocation code.
}

finalize()
finalize() is a method associated with the garbage collector concept. If any object
doesnot refer by any reference variable it means that object is eligible for garbage
collector.
1. Before destroying the object, garbage collector calls finalize() method to cleanup
the activities associated with that object.
2. Once the cleanup activities are completed, immediately the garbage collector
destroy the object.

Just before destroying the object, garbage collector calls the finalize() method for
cleanup activities.

Garbage
collector
object

finalize()
23
Database
Network

finally block and finalize() method both are used to clean up the code
then where is the difference.
finally block meant for try block open resources clean up activities.
finalize() method meant for object related clean up code.

24

You might also like