Oop Using Java - Unit V
Oop Using Java - Unit V
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
}
Exception Types
● All exception types are subclasses of the builtin class Throwable.
● Throwable is at the top of the exception class hierarchy.
● Immediately below Throwable are two subclasses that partition
exceptions into two distinct branches.
○ one branch is headed by Exception, which is used for exceptional conditions
that user programs should catch. also, the class that you will subclass to
create your own custom exception types.
○ the other branch is topped by Error, which defines exceptions that are not
expected to be caught under normal circumstances by your program.
Uncaught Exceptions
● When the java runtime system detects the attempt to divide
by zero, it constructs a new exception object and then
throws this exception.
● This causes the execution of Exc0 to stop, because once an
exception has been thrown, it must be caught by an exception
handler
public class Exc0 {
public static void main(String[] args) { int d
= 0;
int a = 42 / d;
}
}
● 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
java.lang.ArithmeticException: / by
zero at
Exc0.main(Exc0.java: 4)
Using try and catch
● Although the default exception handler provided by the Java
runtime system is useful for debugging, you will usually want to
handle an exception yourself.
● Two benefits:
○ First, it allows you to fix the error
○ Second, it prevents the program from automatically terminating.
● To guard against and handle a runtime error, simply enclose the
code that you want to monitor inside a try block.
● Immediately following the try block, include a catch clause that
specifies the exception type that you wish to catch.
public 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.");
}
}
Handle an exception and move on
import java.util.Random;
/*
* If no command line args are present, the following statement will generate a
* divide-by-zero exception.
*/
int b = 42 / a;
/*
* 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 oob: " + e);
}
} catch (ArithmeticException e) {
System .out.println ("Division by zero: " + e);
}
}
}
public class MethNestTry {
static void nesttry (int a) { public static void main(String[] args) {
try { // nested try block try {
/* int a = args.length;
* If one command line arg is used, then an out-of-bounds
exception will be
/*
* generated by the following statement.
*/ * If no command line args are present, the
if (a == 1) following statement will generate a
a = a / (a - a); // division by zero * divide-by-zero exception.
*/
/*
int b = 42 / a;
* If two command line args are used, then generate an
out-of-bounds exception.
System.out.println("a = " + a);
*/
if (a == 2) {
int [] c = { 1 }; nesttry(a);
c[42] = 99; // generate an out-of-bounds exception } catch (ArithmeticException e) {
} System.out.println("Division by zero: " +
} catch (ArrayIndexOutOfBoundsException e) {
e);
System .out .println ("Array index oob: " +
}
e);
}
}
} }
throw
● It is possible for your program to throw an exception explicitly,
using the throw statement.
public class ThrowDemo
{ static void
demoproc() { try {
throw new NullPointerException("demo");
} catch (NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
class ExceptionDemo {
static void compute (int a) throws ExceptionDemo { System .out
.println ("Called compute(" + a + ")" ); if (a >
10) {
throw new ExceptionDemo (a);
}
System .out .println ("Normal exit" );
}
// add a cause
e.initCause (new ArithmeticException ("cause" ));
throw e;
}
try {
int result = a / b;
vals[10] = 19;
} catch (ArithmeticException |
ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: " +
e);
}
System.out.println("After multi-catch.");
}
}
Using Exceptions
● Exception handling provides a powerful mechanism for
controlling complex programs that have many dynamic runtime
characteristics.
● It is important to think of try, throw and catch as clean ways to
handle errors and unusual boundary conditions in your program’s
logic.
● Unlike some other languages, in which error return codes are used
to indicate failure, Java uses exceptions.
● Thus, when a method can fail, have it throw an exception. This is
a cleaner way to handle failure modes.
End of Unit V: Exception Handling