Unit 03
Exception Handling in Java
12-10-2023 Prepared By Rajeshkumar S AP(SrG) CSE(AIML)
Exception Handling in Java
➢ The Exception Handling in Java is one of the
powerful mechanism to handle the runtime errors
Example:
➢ In Java, an exception is an event that disrupts the normal statement 1;
flow of the program. It is an object which is thrown at statement 2;
runtime. statement 3;
statement 4;
statement 5;//exception occurs
➢ Exception Handling is a mechanism to handle runtime errors statement 6;
such as ClassNotFoundException, IOException, statement 7;
SQLException, RemoteException, etc. statement 8;
statement 9;
statement 10;
➢ The core advantage of exception handling is to maintain the
normal flow of the application. If No Exception Handling
statement 6 to 10 will not be executed
12-10-2023 Prepared By Rajeshkumar S AP(SrG) CSE(AIML)
Hierarchy of Java Exception classes
➢ The [Link] class is the root class of Java Exception hierarchy which is inherited by two subclasses:
Exception and Error.
12-10-2023 Prepared By Rajeshkumar S AP(SrG) CSE(AIML)
Types of Java Exceptions
There are mainly two types of exception
1) Checked Exception
➢ The classes which directly inherit Throwable class except RuntimeException and Error are known as
checked exceptions e.g. IOException, SQLException etc.
➢ Checked exceptions are checked at compile-time.
2) Unchecked Exception
➢ The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
➢ Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
➢ Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
12-10-2023 Prepared By Rajeshkumar S AP(SrG) CSE(AIML)
Java Exceptions Keywords
Keyword Description
Try ➢ Try keyword is used to Specify a block where we should place exception code.
➢ The try block must be followed by either catch or finally.
➢ It means, we can't use try block alone.
Catch ➢ The catch block used to handle the exception
➢ It must be preceded by try block which means we can't use catch block alone.
➢ It can be followed by finally block later.
Finally ➢ The "finally" block is used to execute the important code of the program.
➢ It is executed whether an exception is handled or not.
Throw ➢ The "throw" keyword is used to throw an exception.
Throws ➢ The "throws" keyword is used to declare exceptions.
➢ It doesn't throw an exception.
➢ It specifies that there may occur an exception in the method.
12-10-2023 ➢ It is always used with method
Prepared signature
By Rajeshkumar S AP(SrG) CSE(AIML)
Java Exception Handling Example
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}
catch(ArithmeticException e)
{
[Link](e);
}
//rest code of the program
[Link]("rest of the code...");
}
}
Output:Exception in thread main [Link]
exception:/by zero
rest of the code
12-10-2023 Prepared By Rajeshkumar S AP(SrG) CSE(AIML)
Common Scenarios of Java Exceptions
➢ A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException
➢ 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;
[Link]([Link]());//NullPointerException
➢ A scenario where NumberFormatException occurs
The wrong formatting of any value may occur NumberFormatException..
String s="abc";
int i=[Link](s);//NumberFormatException
➢ A scenario where ArrayIndexOutOfBoundsException occurs
If you are inserting any value in the wrong index, it would result in ArrayIndexOutOfBoundsException
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
12-10-2023 Prepared By Rajeshkumar S AP(SrG) CSE(AIML)
Java try-catch block
Try Block:
➢ Java try block is used to enclose the code that might throw an exception.
➢ If an exception occurs at the particular statement of try block, the rest of the block code will not execute.
➢ So, it is recommended not to keeping the code in try block that will not throw an exception.
➢ Java try block must be followed by either catch or finally block.
Syntax of Java try-catch Syntax of try-finally block
try{ try{
//code that may throw an exception //code that may throw an exception
}catch(Exception_class_Name ref){} }finally{}
Catch Block:
➢ Java catch block is used to handle the Exception by declaring the type of exception within the parameter.
➢ The declared exception must be the parent class exception ( i.e., Exception) or the generated exception type.
➢ However, the good approach is to declare the generated type of exception.
➢ The catch block must be used after the try block only.
➢ You can use multiple catch block with a single try block.
12-10-2023 Prepared By Rajeshkumar S AP(SrG) CSE(AIML)
Java finally block
➢ Java finally block is a block that is used to execute important code such as closing connection, stream etc.
➢ Java finally block is always executed whether exception is handled or not.
➢ Java finally block follows try or catch block.
Usage:
➢ Finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
[Link](data);
}
catch(NullPointerException e){[Link](e);}
finally{[Link]("finally block is always
executed");}
[Link]("rest of the code...");
}
}
12-10-2023 Prepared By Rajeshkumar S AP(SrG) CSE(AIML)
Java throw exception
➢ The Java throw keyword is used to explicitly throw an exception.
➢ We can throw either checked or uncheked exception in java by throw keyword.
➢
➢ The throw keyword is mainly used to throw custom exception
Syntax
throw exception;
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
[Link]("welcome to vote"); Exception in thread main
} [Link]:not valid
public static void main(String args[]){
validate(13);
[Link]("rest of the code...");
}
}
12-10-2023 Prepared By Rajeshkumar S AP(SrG) CSE(AIML)
Java throws keyword
➢ The Java 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.
➢ Which exception should be declared checked exception only
Syntax:
return_type method_name() throws exception_class_name{
//method code
}
Advantage of Java throws keyword
➢ Now Checked Exception can be propagated (forwarded in call stack).
➢ It provides information to the caller of the method about the exception.
12-10-2023 Prepared By Rajeshkumar S AP(SrG) CSE(AIML)
Java throws keyword (Cont..)
import [Link];
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{ exception handled
n(); Normal flow
}catch(Exception e){[Link]("exception handled");
}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
[Link]("normal flow...");
}
}
12-10-2023 Prepared By Rajeshkumar S AP(SrG) CSE(AIML)
Java throws keyword (Cont..)
Exception Handled Exception Declared
import [Link].*; import [Link].*;
class M{ class M{
void method()throws IOException{ void method()throws IOException{
throw new IOException("device error"); [Link]("device operation performed");
} }
} }
public class Testthrows2{ class Testthrows3{
public static void main(String args[]){ public static void main(String args[])throws
try{ IOException{//declare exception
M m=new M(); M m=new M();
[Link](); [Link]();
}catch(Exception
e){[Link]("exception handled");} [Link]("normal flow...");
}
[Link]("normal flow..."); }
}
} Output: Runtime Exception
Output: exception handled
12-10-2023 Prepared By Rajeshkumar S AP(SrG) CSE(AIML)
Normal flow