Exception Handling in Java
Exception Handling in Java
www.tothenew.com
Agenda❖ Errors & Exceptions❖ Stack Trace❖ Types of Exceptions❖ Exception Handling❖ try-catch-finally blocks❖ try with resources❖ Multiple Exceptions in Single Catch❖ Advantages of Exception Handling❖ Custom exceptions
www.tothenew.com
Exceptions➔ An "exceptional condition" that alters the normal program flow➔ Derive from class Exception➔ Exception is said to be "thrown" and an Exception Handler "catches" it➔ Includes File Not Found, Network connection was lost, etc.
Errors➔ Represent unusual situations that are not caused by, and are external
to, the application➔ Application won't be able to recover from an Error, so these aren't
required to handle➔ Includes JVM running out of memory, hardware error, etc
www.tothenew.com
Stack Trace➔ A list of the method calls that the application was in the middle of when an
Exception was thrown.
➔ Example : Book.java public String getTitle() {
System.out.println(title.toString()); <-- line 16 return title;
}
➔ Exception in thread "main" java.lang.NullPointerException at com.example.myproject.Book.getTitle(Book.java:16)at com.example.myproject.Author.getBookTitles(Author.java:25)at com.example.myproject.Bootstrap.main(Bootstrap.java:14)
www.tothenew.com
What exception is not
➔ Exception is not a Message to be shown in the UI
➔ Exceptions are for programmers and support staff.
➔ For displaying in UI use externalized strings
www.tothenew.com
Types of Exceptions➔ Checked Exceptions
◆ Checked at compile time◆ Must be either handled or
specified using throws keyword
➔ Unchecked Exceptions◆ Not checked at compile time◆ Also called as Runtime Exceptions
www.tothenew.com
Checked Exception Example➔ import java.io.*;
class Main {
public static void main(String[] args) { FileReader file = new FileReader("a.txt"); BufferedReader fileInput = new BufferedReader(file); }
}
➔ Compilation Error:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code -
unreported exception java.io.FileNotFoundException; must be caught or declared to be
thrown
at Main.main(Main.java:5)
www.tothenew.com
Runtime Exception Example➔ class Main {
public static void main(String args[]) { int x = 0; int y = 10; int z = y/x; }
}
➔ Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.main(Main.java:5)
Java Result: 1
www.tothenew.com
Exception Handling➔ Mechanism to handle runtime malfunctions➔ Transferring the execution of a program to an appropriate exception
handler when an exception occurs
Java Exception Handling Keywords◆ try◆ catch◆ finally◆ throw◆ throws
www.tothenew.com
try-catch blocks➔ try block :
◆ Used to enclose the code that might throw an exception. ◆ Must be used within the method.◆ Java try block must be followed by either catch or finally block.
➔ catch block◆ Java catch block is used to handle the Exception. It must be used after the
try block only.◆ You can use multiple catch block with a single try.
Syntax of java try-catch
try{
//code that may throw exception
}catch(Exception_class_Name ref){
}
www.tothenew.com
Examplepublic class Testtrycatch{
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){
System.out.println(e);
}
System.out.println("Executing rest of the code...");
}
}
Output :
Exception in thread main java.lang.ArithmeticException:/ by zero
Executing rest of the code...
www.tothenew.com
finally block➔ Follows a try block.➔ Always executes, whether or not an exception has occurred.➔ Allows you to run any cleanup-type statements that you want to execute, no
matter what happens in the protected code.➔ Executes right before the return executes present in try block.
Syntax of try-finally block:
try{
// Protected Code that may throw exception
}catch(Exception ex){
// Catch block may or may not execute
}finally{
// The finally block always executes.
}
www.tothenew.com
Try with resources
➔ JDK 7 introduces a new version of try statement known as try-with-resources statement. This feature add another way to exception handling with resources management,it is also referred to as automatic resource management.
try(resource-specification){
//use the resource }catch() {...}
www.tothenew.com
Multi catch block➔ To perform different tasks at the occurrence of different Exceptions
➔ At a time only one Exception is occurred and at a time only one catch block is executed.
➔ All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException
must come before catch for Exceptionpublic class TestMultipleCatchBlock{ public static void main(String args[]){ try{ int a[]=new int[5]; a[5]=30/0; } catch(ArithmeticException e){System.out.println("task1 is completed");} catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");} catch(Exception e){System.out.println("common task completed");} System.out.println("rest of the code..."); } }
Output:
task1 completed
rest of the code...
www.tothenew.com
Multiple Exceptions in Single Catch
Since Java 7, more than one exceptions can be handled using a single catch block
try{
// Code that may throw exception
} catch (IOException|FileNotFoundException ex) {
logger.log(ex);
}
Bytecode generated by compiling a catch block that handles multiple exception
types will be smaller (and thus superior) than 2 different catch blocks.
www.tothenew.com
throw keyword➔ throw :
◆ Used to explicitly throw an exception◆ Can be used to throw checked, unchecked and custom exception
public class TestThrow1{ static void validate(int age){ if(age<18) throw new ArithmeticException("not valid"); else System.out.println("welcome to vote"); } public static void main(String args[]){ validate(13); System.out.println("rest of the code..."); } }
Output:
Exception in thread main java.lang.ArithmeticException:not valid
www.tothenew.com
throws keyword➔ throws :
◆ Used to declare an exception◆ 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.
import java.io.IOException; class Testthrows{ void secondMethod() throws IOException {throw new IOException("device error");//checked exception
} void firstMethod() throws IOException {secondMethod();
} public static void main(final String args[]) {final Testthrows obj = new Testthrows();try { obj.firstMethod();} catch (final Exception e) { System.out.println("exception handled");}System.out.println("normal flow...");
}
}
Output:exception handled
normal flow...
www.tothenew.com
Exception Handling with Method Overriding➔ If the superclass method does not declare an exception, subclass overridden method cannot declare the
checked exception but it can declare unchecked exception.import java.io.*;
class Parent{
void msg(){System.out.println("parent");}
}
class TestExceptionChild extends Parent{
void msg()throws IOException{
System.out.println("TestExceptionChild");
}
public static void main(String args[]){
Parent parent=new TestExceptionChild();
parent.msg();
}
}
Output:
Compile Time Error
import java.io.*;
class Parent{
void msg(){System.out.println("parent");}
}
class TestExceptionChild1 extends Parent{
void msg()throws ArithmeticException{
System.out.println("child");
}
public static void main(String args[]){
Parent p=new TestExceptionChild1();
p.msg();
}
}
Output:
child
www.tothenew.com
Exception Handling with Method Overriding➔ If the superclass method declares an exception, subclass overridden method can declare same, subclass
exception or no exception but cannot declare parent exception.import java.io.*;
class Parent{
void msg()throws ArithmeticException{System.out.println("parent");}
}
class TestExceptionChild extends Parent{
void msg()throws Exception{System.out.println("child");}
public static void main(String args[]){
Parent p=new TestExceptionChild();
try{
p.msg();
}catch(Exception e){}
}
}
Output:
Compile Time Error
import java.io.*;
class Parent{
void msg()throws Exception{System.out.println("parent");}
}
class TestExceptionChild1 extends Parent{
void msg()throws ArithmeticException{System.out.println("child");}
public static void main(String args[]){
Parent p=new TestExceptionChild1();
try{
p.msg();
}catch(Exception e){}
}
}
Output:
child
www.tothenew.com
Advantages of Exception Handling
➔ To maintain the normal flow of the application
➔ Separating Error-Handling Code from "Regular" Code
➔ Propagating Errors Up the Call Stack
➔ Grouping and Differentiating Error Types
www.tothenew.com
Custom Exceptions➔ If you are creating your own Exception that is known as custom exception
or user-defined exception. Java custom exceptions are used to customize the exception according to user need.
➔ By the help of custom exception, you can have your own exception and message.
➔ To create a custom checked exception, we have to sub-class from the java.lang.Exception class. And that’s it! Yes, creating a custom exception in java is simple as that!
public class CustomException extends Exception{}