You are on page 1of 34

Exception Handling

National Institute of Technology Puducherry


Manjith B.C.
• An exception is an abnormal condition that arises in a code sequence
at run time.
Uncaught Exceptions
class Exc0 { Output
public static void main(String args[]) { java.lang.ArithmeticExce
ption: / by zero
int d = 0; at
int a = 42 / d; Exc0.main(Exc0.java:4)
}
}
• Java run-time system detects the attempt to divide by zero, it constructs a new
exception object and then throws this exception
• the exception is caught by the default handler provided by the Java run-time
system
• The default handler displays a string describing the exception, prints a stack trace
from the point at which the exception occurred, and terminates the program.
Using try and catch
• Although the default exception handler provided by the Java run-time
system is useful for debugging, you will usually want to handle an
exception yourself.
• it allows you to fix the error
• it prevents the program from automatically terminating
class Exc2 {
public static void main(String args[]) { Output:
Division by zero.
int d, a; After catch
try { // monitor a block of code. statement.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
Displaying a Description of an Exception
catch (ArithmeticException e) {
System.out.println("Exception: " + e);
a = 0; // set a to zero and continue
}
Built-in exceptions
• ArithmeticException
It is thrown when an exceptional condition has occurred in an arithmetic operation.
• ArrayIndexOutOfBoundsException
It is thrown to indicate that an array has been accessed with an illegal index. The index is either
negative or greater than or equal to the size of the array.
• ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not found
• FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
• IOException
It is thrown when an input-output operation failed or interrupted
• InterruptedException
It is thrown when a thread is waiting , sleeping , or doing some processing , and it is interrupted.
• NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
• NoSuchMethodException
It is thrown when accessing a method which is not found.
• NullPointerException
This exception is raised when referring to the members of a null
object. Null represents nothing
• NumberFormatException
This exception is raised when a method could not convert a string
into a numeric format.
• RuntimeException
This represents any exception which occurs during runtime.
• StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either
negative than the size of the string
Examples of Built-in Exception
• Arithmetic exception
class ArithmeticException_Demo
{
public static void main(String args[])
{ Output:
try {
int a = 30, b = 0; Can't divide a number by 0
int c = a/b; // cannot divide by zero
System.out.println ("Result = " + c);
}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number by 0");
}
}
}
NullPointer Exception
class NullPointer_Demo
{
public static void main(String args[])
{
Output:
try {
String a = null; //null value NullPointerException..
System.out.println(a.charAt(0));
} catch(NullPointerException e) {
System.out.println("NullPointerException..");
}
}
}
StringIndexOutOfBound Exception
class StringIndexOutOfBound_Demo
{
public static void main(String args[])
{ Output:
try {
String a = "This is like chipping "; // length is 22 StringIndexOutOfBoundsException
char c = a.charAt(24); // accessing 25th element
System.out.println(c);
}
catch(StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException");
}
}
}
FileNotFound Exception
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo { Output:
public static void main(String args[]) {
try { File does not exist
// Following file does not exist
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
} catch (FileNotFoundException e) {
System.out.println("File does not exist");
}
}
}
NumberFormat Exception
class NumberFormat_Demo
{
public static void main(String args[]) Output:
{
try { Number format exception
// "akki" is not a number
int num = Integer.parseInt ("akki") ;
System.out.println(num);
} catch(NumberFormatException e) {
System.out.println("Number format exception");
}
}
}
ArrayIndexOutOfBounds Exception
class ArrayIndexOutOfBound_Demo
{
public static void main(String args[]) Output:
{
try{ Array Index is Out Of Bounds
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("Array Index is Out Of Bounds");
}
}
}
Multiple catch
• In some cases, more than one exception could be raised by a single
piece of code. To handle this type of situation, you can specify two or
more catch clauses, each catching a different type of exception.
When an exception is thrown, each catch statement is inspected
• in order, and the first one whose type matches that of the exception
is executed. After one catch statement executes, the others are
bypassed, and execution continues after the try / catch block.
class MultipleCatches {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
Nested try Statements
class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
int b = 42 / a;
System.out.println("a = " + a);
try { // nested try block
if(a==1) a = a/(a-a); // division by zero
if(a==2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}
C:\>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One
a=1
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One Two
a=2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException:42
throw
• It is possible for your program to throw an exception explicitly, using
the throw statement
• throw ThrowableInstance;
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}
throws
• If a method is capable of causing an exception that it does not handle,
it must specify this behavior so that callers of the method can guard
themselves against that exception.
• A throws clause lists the types of exceptions that a method might
throw.
type method-name(parameter-list) throws exception-list
{
// body of method
}
• In a program, if there is a chance of rising an exception then compiler
always warn us about it and compulsorily we should handle that
checked exception, Otherwise we will get compile time error
saying unreported exception XXX must be caught or declared to be
thrown. To prevent this compile time error we can handle the
exception in two ways:
• By using try catch
• By using throws keyword
// Java program to illustrate error in case
// of unhandled exception
Output:
class tst
{ error: unreported exception InterruptedException; must be
public static void main(String[] args) caught or declared to be thrown
{
Thread.sleep(10000);
System.out.println("Hello");
}
}
// Java program to illustrate throws
class tst
{
public static void main(String[] args)throws InterruptedException
{
Thread.sleep(10000);
System.out.println("Hello "); Output:
}
Hello
}
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
Important points to remember about throws keyword:
• throws keyword is required only for checked exception and usage of
throws keyword for unchecked exception is meaningless.
• throws keyword is required only to convince compiler and usage of
throws keyword does not prevent abnormal termination of program.
• By the help of throws keyword we can provide information to the
caller of the method about the exception
Checked and unchecked exceptions
• Checked: are the exceptions that are checked at compile time
• FileNotFoundException
• IOException
• If some code within a method throws a checked exception, then the
method must either handle the exception or it must specify the
exception using throws keyword.
Checked Exception Handling
Method 1: Declare the exception using throws keyword
• public static void main(String args[]) throws IOException,
FileNotFoundException

Method 2: Handle them using try-catch blocks


Unchecked exceptions
• if your program is throwing an unchecked exception and even if you
didn’t handle/declare that exception, the program won’t give a
compilation error.
• Most of the times these exception occurs due to the bad data
provided by user during the user-program interaction
• Unchecked exceptions are direct sub classes
of RuntimeException class
• ArrayIndexOutOfBoundsException
• ArithmeticException
• IllegalArgumentException
User-Defined Exceptions
• Sometimes, the built-in exceptions in Java are not able to describe a
certain situation. In such cases, user can also create exceptions which
are called ‘user-defined Exceptions’.
class ExceptionDemo
class MyException extends Exception {
{ public static void main(String s[])
MyException() {
{} try
MyException(String str) {
{ MyData d=new MyData(10,250);
super(str); if(d.bal<500)
}
{
} MyException e=new MyException("Balance less than
class MyData 500");
{ throw e;
int accno,bal; }
MyData(int acno, int b) }
{
accno=acno; catch(MyException me)
bal=b; {
} me.printStackTrace();
} }
}
}
finally
• executed after a try/catch block has completed
• finally block will execute whether or not an exception is thrown
• If an exception is thrown, the finally block will execute even if no
catch statement matches the exception
• finally clause is optional
• each try statement requires at least one catch or a finally clause
public class DemoFinal
{
public static void main(String args[])
{
try
Output:
{
javac DemoFinal.java
int a=args.length;
java DemoFinal
int x=42/a;
java.lang.ArithmeticException: / by zero
}
Finally block executed
catch(ArithmeticException e)
{
System.out.println(e);
}
finally
{
System.out.println("Finally block executed");
}
}
}
Uses of Exception handling
• Database connectivity- to predict failure- handle unreachable server
etc. (banking)
• OS- recover from deadlock
• To show a pop-up for error in file opening than showing just
exception error

You might also like