Exception Handling
Exception Handling
• An exception is an abnormal condition that
arises in a code sequence at run time.
• In other words, an exception is a run-time
error.
• Exceptions can be generated by the Java run-
time system, or they can be manually
generated by your code.
• Exceptions thrown by Java relate to fundamental
errors that violate the rules of the Java language
or the constraints of the Java execution
environment.
• Manually generated exceptions are typically used
to report some error condition to the caller of a
method.
• Java exception handling is managed via five
keywords: try, catch, throw, throws, and finally
• The general form :
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed before try block ends
}
• All exception types are subclasses of the built-
in class Throwable.
• Exception, Error are the subclasses of
Throwable class.
Exception
• This is also the class that you will subclass to
create your own custom exception types.
• Eg:
division by zero
invalid array indexing.
Error
• which defines exceptions that are not
expected to be caught under normal
circumstances by your program.
• Eg:
Stack overflow
Using try and catch
• exception handler allows you to fix the error.
Second, it prevents the program from
automatically terminating.
• To guard against and handle a run-time error,
simply enclose the code that you want to
monitor inside a try block.
• If an exception occurs within the try block, it is
thrown.
• Your code can catch this exception (using
catch) and handle it in some rational manner.
Sample
class Exc2 {
public static void main(String args[]) {
int d, a;
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.");
}
}
• Output:
Division by zero.
After catch statement.
• Once an exception is thrown, program control
transfers out of the try block into the catch
block.
• Once the catch statement has executed,
program control continues with the next line
in the program following the entire try/catch
mechanism.
• The statements that are protected by try must
be surrounded by curly braces.
Displaying a Description of an
Exception
• Throwable overrides the toString( ) method
(defined by Object) so that it returns a string
containing a description of the exception.
Multiple catch Clauses
• 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.
• After one catch statement executes, the
others are bypassed, and execution continues
after the try/catch block
Sample
class MultiCatch {
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.");
} }
• When you use multiple catch statements, it is
important to remember that exception
subclasses must come before any of their
superclasses.
• Checked exceptions :
– Checked Exceptions forces programmers to deal
with the exception that may be thrown.
– Checked exceptions must be caught at compile
time.
• Unchecked exceptions:
– Unchecked exceptions , however, the compiler
doesn’t force the programmers to either catch the
exception or declare it in a throws clause.
Nested try Statements
• The try statement can be nested.
• Sample
class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
/* If no command-line args are present, the following statement will
generate a divide-by-zero exception. */
int b = 42 / a;
System.out.println("a = " + a);
try { // nested try block
/* If one command-line arg is used, then a divide-by-zero exception
will be generated by the following code. */
if(a==1) a = a/(a-a); // division by zero
/* If two command-line args are used,
then generate an out-of-bounds exception. */
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);
}
}
}
• Output:
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
throw
• It is possible for your program to throw an
exception explicitly, using the throw
statement.
• The general form :
throw ThrowableInstance;
• ThrowableInstance must be an object of type
Throwable or a subclass of Throwable.
• The flow of execution stops immediately after
the throw statement; any subsequent
statements are not executed.
• The nearest enclosing try block is inspected to
see if it has a catch statement that matches
the type of the exception.
Sample
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
}
}
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
behaviour so that callers of the method can
guard themselves against that exception.
• You do this by including a throws clause in the
method’s declaration.
• The general form:
– type method-name(parameter-list) throws
exception-list
– {
– // body of method
– }
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);
}
} }
finally
• Any code that absolutely must be executed
before a method returns is put in a finally
block.
• The finally block will execute whether or not
an exception is thrown.
• This can be useful for closing file handles and
freeing up any other Resources.
• The finally clause is optional.
Sample
class FinallyDemo {
// Through an exception out of the method.
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
} finally {
System.out.println("procA's finally");
}
}
Java’s Built-in Exceptions
• unchecked exceptions - because the compiler
does not check to see if a method handles or
throws these exceptions.
• checked exceptions- Java defines several other
types of exceptions that relate to its various
class libraries
Unchecked Exception
Checked Exceptions
Creating Your Own Exception
Subclasses
• To create your own exception types to handle
situations specific to your applications, to do
so just define a subclass of Exception.
Sample
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);
}
} }
Chained Exceptions
• The chained exception feature allows you to
associate another exception with an
exception.

Java exception handling

  • 1.
  • 2.
    Exception Handling • Anexception is an abnormal condition that arises in a code sequence at run time. • In other words, an exception is a run-time error. • Exceptions can be generated by the Java run- time system, or they can be manually generated by your code.
  • 3.
    • Exceptions thrownby Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment. • Manually generated exceptions are typically used to report some error condition to the caller of a method. • Java exception handling is managed via five keywords: try, catch, throw, throws, and finally
  • 4.
    • The generalform : try { // block of code to monitor for errors } catch (ExceptionType1 exOb) { // exception handler for ExceptionType1 } catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 } // ... finally { // block of code to be executed before try block ends }
  • 5.
    • All exceptiontypes are subclasses of the built- in class Throwable. • Exception, Error are the subclasses of Throwable class.
  • 6.
    Exception • This isalso the class that you will subclass to create your own custom exception types. • Eg: division by zero invalid array indexing.
  • 7.
    Error • which definesexceptions that are not expected to be caught under normal circumstances by your program. • Eg: Stack overflow
  • 8.
    Using try andcatch • exception handler allows you to fix the error. Second, it prevents the program from automatically terminating. • To guard against and handle a run-time error, simply enclose the code that you want to monitor inside a try block.
  • 9.
    • If anexception occurs within the try block, it is thrown. • Your code can catch this exception (using catch) and handle it in some rational manner.
  • 10.
    Sample class Exc2 { publicstatic void main(String args[]) { int d, a; 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."); } }
  • 11.
    • Output: Division byzero. After catch statement. • Once an exception is thrown, program control transfers out of the try block into the catch block. • Once the catch statement has executed, program control continues with the next line in the program following the entire try/catch mechanism.
  • 12.
    • The statementsthat are protected by try must be surrounded by curly braces.
  • 13.
    Displaying a Descriptionof an Exception • Throwable overrides the toString( ) method (defined by Object) so that it returns a string containing a description of the exception.
  • 14.
    Multiple catch Clauses •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. • After one catch statement executes, the others are bypassed, and execution continues after the try/catch block
  • 15.
    Sample class MultiCatch { publicstatic 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."); } }
  • 16.
    • When youuse multiple catch statements, it is important to remember that exception subclasses must come before any of their superclasses.
  • 17.
    • Checked exceptions: – Checked Exceptions forces programmers to deal with the exception that may be thrown. – Checked exceptions must be caught at compile time. • Unchecked exceptions: – Unchecked exceptions , however, the compiler doesn’t force the programmers to either catch the exception or declare it in a throws clause.
  • 18.
    Nested try Statements •The try statement can be nested. • Sample class NestTry { public static void main(String args[]) { try { int a = args.length; /* If no command-line args are present, the following statement will generate a divide-by-zero exception. */ int b = 42 / a; System.out.println("a = " + a); try { // nested try block /* If one command-line arg is used, then a divide-by-zero exception will be generated by the following code. */ if(a==1) a = a/(a-a); // division by zero
  • 19.
    /* If twocommand-line args are used, then generate an out-of-bounds exception. */ 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); } } }
  • 20.
    • Output: C:>java NestTry Divideby 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
  • 21.
    throw • It ispossible for your program to throw an exception explicitly, using the throw statement. • The general form : throw ThrowableInstance; • ThrowableInstance must be an object of type Throwable or a subclass of Throwable.
  • 22.
    • The flowof execution stops immediately after the throw statement; any subsequent statements are not executed. • The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of the exception.
  • 23.
    Sample class ThrowDemo { staticvoid demoproc() { try { throw new NullPointerException("demo"); } catch(NullPointerException e) { System.out.println("Caught inside demoproc."); } } public static void main(String args[]) { try { demoproc(); } catch(NullPointerException e) { System.out.println("Recaught: " + e); } } }
  • 24.
    throws • If amethod is capable of causing an exception that it does not handle, it must specify this behaviour so that callers of the method can guard themselves against that exception. • You do this by including a throws clause in the method’s declaration. • The general form: – type method-name(parameter-list) throws exception-list – { – // body of method – }
  • 25.
    class ThrowsDemo { staticvoid 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); } } }
  • 26.
    finally • Any codethat absolutely must be executed before a method returns is put in a finally block. • The finally block will execute whether or not an exception is thrown. • This can be useful for closing file handles and freeing up any other Resources. • The finally clause is optional.
  • 27.
    Sample class FinallyDemo { //Through an exception out of the method. static void procA() { try { System.out.println("inside procA"); throw new RuntimeException("demo"); } finally { System.out.println("procA's finally"); } }
  • 28.
    Java’s Built-in Exceptions •unchecked exceptions - because the compiler does not check to see if a method handles or throws these exceptions. • checked exceptions- Java defines several other types of exceptions that relate to its various class libraries
  • 29.
  • 30.
  • 31.
    Creating Your OwnException Subclasses • To create your own exception types to handle situations specific to your applications, to do so just define a subclass of Exception.
  • 32.
    Sample class MyException extendsException { 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 + ")");
  • 33.
    if(a > 10) thrownew 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); } } }
  • 34.
    Chained Exceptions • Thechained exception feature allows you to associate another exception with an exception.