0% found this document useful (0 votes)
28 views24 pages

5 Exception Handling

Exception Handling

Uploaded by

hasibshahriar04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views24 pages

5 Exception Handling

Exception Handling

Uploaded by

hasibshahriar04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Exception Handling

Exception Handling Fundamentals


w An exception is an abnormal condition that arise in
a code sequence at run time.
w An exception is a run-time error.
w Java exception handling brings runtime error
management into object-oriented world.
w A java exception is an object that describes an
exceptional condition that occurred in a piece of
code.
w When an exceptional condition arise
n An object represents that exception is created.
n Thrown in the method that caused the error.
n The method can handle the exception or pass it on.
n At some point the exception is caught and processed.
Keywords
w Exception handling is managed by five keyword
n try:
l Program statement that you want to monitor for exception are
contained within a try block.
n catch:
l Your code can catch the exception and handle it.
n throw:
l Use to throw an exception manually.
n throws:
l A method that may throw an exception must be specified by a
throws clause.
n finally (can’t be used without try):
l Any code that must be executed before a method returns is put in
a finally block.
w 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;
}
}
w Java runtime system detects the attempted division by zero
n Construct new exception object and then throws this exception.
n The execution will stop.
n It must be caught and handled immediately.
n Here exception is caught by default exception handler.
n 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 Type

Class name method name line number where exception is occurred


Using Try and Catch
class Exc2 {
public static void main(String args[]) {
Division by zero.
int d, a;
After catch statement.
try { // monitor a block of code.
d = 0; After catching exception, program execution
a = 42 / d; will continue from after catch statement(s)
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.");
}
}
w A try and its catch block form an unit.
w 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(); Generates Random number of 7/8 digits
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

w All java exception class inherits, either directly or


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

Exception Error

RuntimeException IOException AWTError ThreadDeath OutOfMemoryError

Compile time exception / Other Exception


Checked & Unchecked Exception
w Unchecked Exception
n All exception types that are directly or indirectly
subclass of class RuntimeException.
w Checked Exception
n All class that inherits from class Exception but
not class RuntimeException.
Multiple catch Clauses
// Demonstrate multiple catch statements.
class MultiCatch { •If more than one exception could
public static void main(String args[]) { be raised in single piece of code.
try { We can specify multiple catch
int a = args.length; block.
System.out.println("a = " + a); •After one catch statement
int b = 42 / a; executes, the other are bypassed.
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.");
}
}
w java MultiCatch
Output:
a=0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
w java MultiCatch 5
Output:
a=1
Array index oob: java.lang.ArrayIndexOutOfBoundsException: 42
After try/catch blocks.
w When you use multiple catch statement
n Remember that exception subclasses must come before any of their superclasses.
n 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. */ {
class MethNestTry { try {
static void nesttry(int a) { int a = args.length;
try { // nested try block
/* If one command line arg is used, then an /* If no command line args are
divide-by-zero exception will be generated present, the following statement will
by the following code. */ generate a divide-by-zero exception. */
if(a==1) a = a/(a-a); // division by zero int b = 42 / a;

/* If two command line args are used then System.out.println("a = " + a);
generate an out-of-bounds exception. */
if(a==2) {
nesttry(a);
int c[] = { 1 };
} catch(ArithmeticException e) {
c[42] = 99; // generate an out-of-bounds
exception System.out.println("Divide by 0: "
+ e);
}
}
} catch(ArrayIndexOutOfBoundsException
e) { }
System.out.println("Array index out-of- }
bounds: " + e);
}
}
throw Keyword
w Using “throw” statement
n It is possible for your program to throw an
exception explicitly.
n General form: throw ThrowableInstance;
l 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 inside demoproc.
} Recaught: java.lang.NullPointerException: demo

public static void main(String args[]) {


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

class ThrowsDemo { Throws not used;


So it will show
static void throwOne() {
error
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 throwOne.
}
Caught java.lang.IllegalAccessException: demo
finally Keyword
w There are some code in a program that must be
executed, whether the exception is occurred or not
occurred.
w finally creates a block that will be executed after
try/catch has completed.
w The finally block will be executed whether or not
the exception is thrown.
w This can be useful for closing files handles, freeing
up any other resources, closing links.
w The finally block is optional.
w Each try statement requires at least one catch or a
finally clause.
class FinallyDemo { // Execute a try block normally.
// Through an exception out of the static void procC() {
method. try {
static void procA() {
System.out.println("inside procC");
try { inside
System.out.println("inside procA"); } finally { procA
throw new System.out.println("procC's finally"); procA'
RuntimeException("demo"); } s
} finally { finally
}
System.out.println("procA's Except
finally"); ion
} public static void main(String args[]) { caught
} inside
try {
// Return from within a try block. procB
procA();
static void procB() { procB'
try { } catch (Exception e) { s
System.out.println("inside procB"); System.out.println("Exception caught"); finally
return; } inside
} finally { procC
procB();
System.out.println("procB's procC'
finally"); procC(); s
} }} finally
}
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)
} Normal exit
Called compute(20)
Caught MyException[20]

You might also like