Exception Handling in Java
Exception Handling in Java
An exception (or exceptional event) is a problem that arises during the execution
of a program. When an Exception occurs the normal flow of the program is disrupted
and the program/Application terminates abnormally, which is not recommended,
therefore, these exceptions are to be handled.
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error
are known as checked exceptions. For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException,
etc. Unchecked exceptions are not checked at compile-time, but they are checked at
runtime.
3) Error
try block
The try block contains a set of statements that might throw an exception
It must be used within the method.
A try block must be followed by catch blocks or finally block or both.
Example Program1
Example Program2
Multi-catch block
A try block can be followed by one or more catch blocks. Each catch block must contain
a different exception handler.
Java finally block is a block used to execute important code such as closing the
connection, etc.
throw
The throw keyword in Java is used to explicitly throw an exception from a method or
any block of code. We can throw either checked or unchecked exception. The throw
keyword is mainly used to throw custom exceptions.
Example Program
if(age<18)
else
checkAge(13);
System.out.println("End Of Program");
throws
Example program1
int t = a/b;
return t;
try{
System.out.println(division(15,0));
catch(ArithmeticException e){
Example program2
class ThrowsExecp
try
fun();
catch(IllegalAccessException e)
System.out.println("caught in main.");
Custom Exception
String message;
CustomException(String str) {
message = str;
try {
} catch(CustomException e) {
System.out.println(e);
Output
System.out.println(e);
}
System.out.println("Continuing execution...");
}
}
OUTPUT
2. Program to handle Null Pointer Exception and use the “finally” method to
display a message to the user.
public class NPException
{
public static void main(String[] args) {
String s=null;
try{
System.out.println(s.length());
}catch(NullPointerException e)
{
System.out.println(e);
}
finally{
System.out.println("This will always executes");
}
Output
java.lang.NullPointerException
This will always executes
Happy Coding