Exception Handling Java
Exception Handling Java
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
Throwable
Exception Error
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
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]