You are on page 1of 24

Exception Handling

Exception Handling Fundamentals


 An exception is an abnormal condition that arise in
a code sequence at run time.
 An exception is a run-time error.
 Java exception handling brings runtime error
management into object-oriented world.
 A java exception is an object that describes an
exceptional condition that occurred in a piece of
code.
 When an exceptional condition arise
 An object represents that exception is created.
 Thrown in the method that caused the error.
 The method can handle the exception or pass it on.
 At some point the exception is caught and processed.
Keywords
 Exception handling is managed by five keyword
 try:
 Program statement that you want to monitor for exception are
contained within a try block.
 catch:
 Your code can catch the exception and handle it.
 throw:
 Use to throw an exception manually.
 throws:
 A method may throw an exception must be specified by a throws
clause.
 finally:
 Any code that must be executed before a method returns is put in
a finally block.
 General form of an exception handling block:
try{
//block of code to monitor for error
}
catch(ExceptionType1 exOb){
//Exception handler for Exception Type1
}
catch(ExceptionType2 exOb){
//Exception handler for Exception Type2
}
//...
finally{
//block of code to be executed before try block ends
}
Uncaught Exceptions
class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}
 Java runtime system detects the attempted to divided by zero
 Construct new exception object and then throws this exception.
 The execution of Exc0 will stop.
 It must be caught and handle immediately.
 Here exception is caught by default exception handler.
 Print a string describing the exception called stack trace.
Programs Output:

Exception in thread "main"


java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)
Exception
ExceptionType
Type

Class
Classname
name method
methodname
name line
linenumber
numberwhere
whereexception
exceptionisisoccurred
occurred
Using Try and Catch
class Exc2 {
public static void main(String args[]) {
Division
Divisionby
byzero.
zero.
int d, a;
After
Aftercatch
catchstatement.
statement.
try { // monitor a block of code.
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.");
}
}
 A try and its catch block form an unit.
 The scope of the catch clause is restricted to those
statements specified by the immediately preceding try
statement.
import java.util.Random;
class HandleError {
public static void main(String args[]) {
int a=0, b=0, c=0;
Random r = new Random();
for(int i=0; i<32000; i++) {
try {
b = r.nextInt();
c = r.nextInt();
a = 12345 / (b/c);
} catch (ArithmeticException e) {
System.out.println("Division by zero.");
a = 0; // set a to zero and continue
}
System.out.println("a: " + a); }}}
Java Exception Hierarchy

 All java exception class inherits, either directly or


indirectly from class Exception.
 Programmers can extend this hierarchy to create
their own exception class.
 Superclass Throwable
 Subclass Exception
 Exceptional situations
 Should be caught by program
 Subclass Error
 Typically not caught by program
Inheritance hierarchy for
class Throwable

Throwable

Exception Error

RuntimeException IOException AWTError ThreadDeath OutOfMemoryError


Checked & Unchecked Exception

 Unchecked Exception
 All exception types that are directly or indirectly
subclass of class RuntimeException.
 Checked Exception
 All class that inherits from class Exception but
not class RuntimeException.
Multiple catch Clauses
// Demonstrate multiple catch statements.
•IF more than one exception
class MultiCatch {
public static void main(String args[]) {
could be raised in single piece
try { of code. We can specify
int a = args.length; multiple catch block.
System.out.println("a = " + a); •After one catch statement
int b = 42 / a;
executes, the other are
int c[] = { 1 };
c[42] = 99;
bypassed.
} 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.");
}
}
 java MultiCatch
Output:
a=0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
 java MultiCatch 5
Output:
a=1
Array index oob: java.lang.ArrayIndexOutOfBoundsException: 42
After try/catch blocks.
 When you use multiple catch statement
 Remember that exception subclasses must come before any of their superclasses.
 A subclass must come before its superclass in a series of catch statements. If not,
unreachable code will be created and a compile-time error will result.

class SuperSubCatch {
public static void main(String args[]) {
try {
int a = 0;
int b = 42 / a;
} catch(Exception e) {
System.out.println("Generic Exception catch.");
}
/* This catch is never reached because
ArithmeticException is a subclass of Exception. */
catch(ArithmeticException e) { // ERROR - unreachable
System.out.println("This is never reached.");
}
}
}
/* Try statements can be implicitly nested via public static void main(String args[]) {
calls to methods. */ try {
class MethNestTry { int a = args.length;
static void nesttry(int a) {
try { // nested try block /* If no command line args are present,
/* If one command line arg is used, then an divide-the following statement will generate a
by-zero exception will be generated by the divide-by-zero exception. */
following code. */ int b = 42 / a;
if(a==1) a = a/(a-a); // division by zero
System.out.println("a = " + a);
/* If two command line args are used then
generate an out-of-bounds exception. */
nesttry(a);
if(a==2) {
} catch(ArithmeticException e) {
int c[] = { 1 };
System.out.println("Divide by 0: " + e);
c[42] = 99; // generate an out-of-bounds
exception }
} }
} catch(ArrayIndexOutOfBoundsException e) { }
System.out.println("Array index out-of-bounds: " +
e);
}
}
throw Keyword
 Using “throw” statement
 It is possible for your program to throw an
exception explicitly.
 General form: throw ThrowableInstance;
 Here ThrowableInstance must be an object of type
Throwable or a subclass of Throwable.
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // re-throw the exception
} Caught
Caughtinside
insidedemoproc.
demoproc.
} Recaught: java.lang.NullPointerException: demo
Recaught: java.lang.NullPointerException: demo

public static void main(String args[]) {


try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}
throws Keyword
 If a method is capable of causing a exception that it
does not handle
 It must specify its behavior so that caller of this method
can guard against that exception.
 A throws clause
 Lists the types of exceptions that a method might throw.
 This is necessary for all exception, except “Error” or
“RuntimeException” or any of its subclasses.
 All other exception that a method can throw must be
declared in throws clause.
 General form of throws clause
 type method_name(Parameter_list) throws exception_list
{//body of the method
}
 Class hierarchy
 java.lang.Object
 java.lang.Throwable
 java.lang.Exception
 java.lang.IllegalAccessException

class ThrowsDemo {
static void throwOne() {
System.out.println("Inside throwOne.");
throw new NullPointerException("demo");
}
public static void main(String args[]) {
throwOne();
}
}
// This is now correct.
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 (IllegaAccessException e) {
System.out.println("Caught " + e);
}
}
} Inside
InsidethrowOne.
throwOne.
Caught
Caughtjava.lang.IllegalAccessException:
java.lang.IllegalAccessException:demo
demo
finally Keyword
 There are some code in a program that must be
executed, whether the exception is occurred or not
occurred.
 finally creates a block that will be executed after
try/catch has completed.
 The finally block will executed whether or not the
exception is thrown.
 This can be useful for closing files handles any
freeing up any other resources.
 The finally block is optional.
 Each try statement requires at least one catch or a
finally clause.
inside
insideprocA
procA
// Execute a try block normally.
classfinally
procA's
procA's FinallyDemo {
finally
// Through an exception out of the method. static void procC() {
Exception
Exceptioncaught
caught
static void procA() { try {
inside
insideprocB
procB
try { System.out.println("inside procC");
procB's finally
procB'sSystem.out.println("inside
finally procA");
} finally {
inside
insideprocC
throw new RuntimeException("demo");
procC
System.out.println("procC's finally");
procC's } finally {
procC'sfinally
finally
System.out.println("procA's finally"); }
} }
}
public static void main(String args[]) {
// Return from within a try block.
static void procB() { try {
try { procA();
System.out.println("inside procB"); } catch (Exception e) {
return; System.out.println("Exception caught");
} finally {
}
System.out.println("procB's finally");
} procB();
} procC();
}}
Creating own Exception subclass
// This program creates a custom exception type.
class MyException extends Exception {
private int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
class ExceptionDemo {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[]) {
try {
compute(1);
compute(20);
} catch (MyException e) {
System.out.println("Caught " + e);
}
} Called compute(1)
Called compute(1)
} Normal
Normalexit
exit
Called
Calledcompute(20)
compute(20)
Caught
CaughtMyException[20]
MyException[20]

You might also like