KEMBAR78
Chap2 exception handling | PPTX
Chapter2-Exception Handling
Unit 3
contents
• The exception hierarchy
• Exception handling fundamentals
• Try and catch
• The consequences of an uncaught exception
• Using multiple catch statements
• Catching subclass exceptions
• Nested try blocks
• Throwing an exception
• Re-throwing an exception
• Using finally
• Using throws
• Java’s built-in exception
• Creating exception subclasses
introduction
• A exception is an error that occurs at run time.
• An advantage of exception handling is that it automates
much of error handling code that previously had to
entered “by hand” into large program.
• Exception handling streamlines error handling by
allowing your program to define a block of code called an
exception handler, I.e. executed automatically when an
error occurs.
• It is not necessary to manually check the success or
failure of each specific operation or method call.
• If an error occurs, it will be processed by the exception
handler.
• Another reason that exception handling is important is
that java standard exceptions for common program
errors, such as divide-by-zero or file or not found.
• To respond to these errors , your programs must watch
for and handle these exceptions.
• To be a successful Java programmer means that you are
fully capable of navigating Java’s exception handling
subsystem.
The Exception Hierarchy
• In Java, all exceptions are represented by classes.
• All exception classes are derived from a class called
Throwable.
• When an exception occurs in a program, an object of
some type of exception class is generated.
• There are two direct subclasses of Throwable:
Exception and Error
• Exceptions of the type Error are related to the errors that
occur in Java Virtual machine itself and not in your
program.
• These exceptions are usually beyond your control, your
program will not usually deal with them.
• Errors that result from program activity are represented
by subclasses of Exceptions.
• For example: divide- by-zero , array boundary , file
errors fall into this category.
• An important subclass of Exception is
RuntimeException , which is used to represent
various common types of run-time errors.
Exception handling fundamentals
• Java Exception handling has five keywords:
▫ try
▫ catch
▫ throw
▫ Throws
▫ finally
• Program statements that you want to monitor for
exceptions are contained within a try block.
• If an exception occurs within the try block , it is thrown
• Your code can catch this using a catch block and handle
them it in some rational manner.
• System generated exceptions are automatically thrown
by Java runtime system.
• To manually throw the exceptions, use the keyword
throw.
• In some case, an exception that is thrown out of the
method must be specified as such by a throws clause.
• Any code that absolutely must be executed upon exiting
from a try block is put in a finally block.
Using try and catch
• These keywords work together;
• you can’t have a try without a catch, or catch
without a try
try {
// block of code to monitor for errors
}
catch (ExcepType1 exOb) {
// handler for ExcepType1
}
catch (ExcepType2 exOb) {
// handler for ExcepType2
}...
• Here, ExcepType is the type of exception that has
occurred.
• When an exception is thrown, it is caught by its
corresponding catch statement, which then processes the
exception.
• As the general form shows, there can be more than
one catch statement associated with a try.
• The type of the exception determines which catch
statement is executed.
• When an exception is caught, exOb will receive its value.
• Here is an important point: If no exception is thrown,
then a try block ends normally, and all of its catch
statements are bypassed. Execution resumes
with the first statement following the last catch.
• Thus, catch statements are executed only if an
exception is thrown.
A simple exception example
• An error to attempt to index an array beyond its boundaries.
• When this occurs, the JVM throws an
ArrayIndexOutOfBoundsException.
• This program displays the following output:
Before exception is generated.
Index out-of-bounds!
After catch statement.
• the code that you want to monitor for errors is
contained within a try block.
• when an exception occurs the exception is thrown out of
the try block and caught by the catch statement.
• After the catch statement executes, program
control continues with the statements following the
catch.
• it is the job of your exception handler to remedy the
problem that caused the exception so that program
execution can continue normally.
• if no exception is thrown by a try block, no catch
statements will be executed and program control
resumes after the catch statement
The consequences of an Uncaught
Exception
• By having an exception handler, it prevents abnormal
program termination.
• If your program does not catch an exception, then it will
be caught by the JVM.
• JVM exception handler terminates the execution and
displays a stack trace and error message.
// This won't work!
class ExcTypeMismatch {
public static void main(String args[]) {
int nums[] = new int[4];
try {
System.out.println("Before exception is generated.");
// generate an index out-of-bounds exception
nums[7] = 10;
System.out.println("this won't be displayed");
}
/* Can't catch an array boundary error with an
ArithmeticException. */
catch (ArithmeticException exc) {
// catch the exception
System.out.println("Index out-of-bounds!");
}
System.out.println("After catch statement.");
}
}
Exceptions enable you to handle errors
gracefully
• By having an exception handler ,it enables your program
to respond to an error and then continue running.
• If a division by zero occurs, an ArithmeticException
is generated.
• In the following program, this exception us handled by
reporting the error then continuing with the execution.
• Thus attempting to divide by zero does not cause an
abrupt run-time error resulting a termination of the
program.
• Makes another important point, once an exception has
been handled, it is removed for the system.
• In program , each pass through the loop enters the try
block new, any prior exception have been handled.
• This enables your program to handle repeated errors.
Using multiple catch statements
• We can associate more than one catch statement with a
try.
• Each catch must catch a different type of exception.
• Program that catch both array boundary and divide by
zero errors
Catching subclass exceptions
• A catch clause for a superclass will also match any of its
subclasses.
• Superclass of all exceptions is Throwable , to catch all
possible exceptions.
• If you want to catch exceptions of both superclass type
and a subclass type put the subclass first in the catch
sequence.
• If you don’t then the superclass catch will also catch all
derived classes.
• Putting the super class first causes unreachable code to
be created, since the subclass catch clause can never
execute.
• In java, unreachable code is an error.
output
Nested Try blocks
• One try block can be nested within another.
• An exception generated within inner try block that is not
caught by the catch block associated with the try
propagated to the outer try block
• Ex: ArrayIndecOutOfBoundException is not caught by
the inner catch , but the outer catch
Throwing an exception
• It is possible to throw an exception by using throw
statement.
• General statement is:
▫ throw exceptObj;
• Here the exceptObj should be an object of exception
class derived from Throwable.
• An example that illustrates the throw statement by
manually throwing an ArithmeticException
Rethrowing an exception
• An exception caught by one catch statement can be
rethrown so that it can be caught by an outer catch.
• It allows multiple handlers access to the exception.
• When you rethrow an exception, it will not be recaught
by the same catch statement.
• It will propagate to the next catch statement.
class RethrowDemo {
public static void main(String args[]) {
try {
Rethrow.genException();
}
catch(ArrayIndexOutOfBoundsException exc) {
// recatch exception
System.out.println("Fatal error – " +
"program terminated.");
}
}
}
Closer look at Throwable class
Using finally
• When you want to define a block of code that will execute
when a try/catch block is left.
• A method that has opened a file or a network connection
that needs to be closed.
• To specify a block of code to execute when a try/catch
block is exited, included a finally block at the end of
try/catch sequence.
• General form of try/catch that includes finally is as
shown below.
• The finally block will be executed whenever execution
leaves a try/catch block, no matter what condition causes
it.
• i.e. whether try block ends normally or because of an
exception, last code that will be executed is defined by
finally.
• Example of using the concept of finally
class FinallyDemo {
public static void main(String args[]) {
for(int i=0; i < 3; i++) {
UseFinally.genException(i);
System.out.println();
}
}
}
• Here is the output produced by the program.
Receiving 0
Can't divide by Zero!
Leaving try.
Receiving 1
No matching element found.
Leaving try.
Receiving 2
Leaving try.
Using throws
• If a method generates an exception that it does not
handle, it must declare that exception in throws clause.
ret_type methname(param_list) throws excp_list{
//body
}
▫ here excp_list is a comma sepearted list of exceptions
that the method might throw outside of itself.
▫ When performing keyboard input, you should add the
clause
 throws java.IOException
• An example that handles IOException.
• It creates a method called prompt(), which displays a
prompting message and then reads a character from the
keyboard.
• Since the input is being performed , an IOException
might occur.
• prompt() uses a throws() which means that the calling
method must handle it.
• The following example, the calling method is main(), and
deals with the error.
Java built-in exceptions
• Inside standard package java.lang , Java defines several
exception classes.
• There are two kinds of exceptions
• Checked exceptions
▫ The exceptions defined by java.lang that must be
included in a methods throws list if that method can
generate one of these exceptions and does not handle
it itself.
• Unchecked exceptions
▫ if the compiler does not check to see if a method
handles or throws these exceptions.
Creating Exception subclasses
• Creating an exception is easy
• Just define a subclass of exception class.
• This subclass need not implement anything, it inherits
those methods provided by Throwable class.
• Exception called NonIntResultException , which is
generated when the result of dividing two integer values
produce a result with a fractional and override of the
toString() method, allowing the description to be printed
using println() method.
Chap2 exception handling
Chap2 exception handling
Chap2 exception handling

Chap2 exception handling

  • 1.
  • 2.
    contents • The exceptionhierarchy • Exception handling fundamentals • Try and catch • The consequences of an uncaught exception • Using multiple catch statements • Catching subclass exceptions • Nested try blocks • Throwing an exception • Re-throwing an exception • Using finally • Using throws • Java’s built-in exception • Creating exception subclasses
  • 3.
    introduction • A exceptionis an error that occurs at run time. • An advantage of exception handling is that it automates much of error handling code that previously had to entered “by hand” into large program. • Exception handling streamlines error handling by allowing your program to define a block of code called an exception handler, I.e. executed automatically when an error occurs. • It is not necessary to manually check the success or failure of each specific operation or method call. • If an error occurs, it will be processed by the exception handler.
  • 4.
    • Another reasonthat exception handling is important is that java standard exceptions for common program errors, such as divide-by-zero or file or not found. • To respond to these errors , your programs must watch for and handle these exceptions. • To be a successful Java programmer means that you are fully capable of navigating Java’s exception handling subsystem.
  • 5.
    The Exception Hierarchy •In Java, all exceptions are represented by classes. • All exception classes are derived from a class called Throwable. • When an exception occurs in a program, an object of some type of exception class is generated. • There are two direct subclasses of Throwable: Exception and Error • Exceptions of the type Error are related to the errors that occur in Java Virtual machine itself and not in your program. • These exceptions are usually beyond your control, your program will not usually deal with them.
  • 6.
    • Errors thatresult from program activity are represented by subclasses of Exceptions. • For example: divide- by-zero , array boundary , file errors fall into this category. • An important subclass of Exception is RuntimeException , which is used to represent various common types of run-time errors.
  • 7.
    Exception handling fundamentals •Java Exception handling has five keywords: ▫ try ▫ catch ▫ throw ▫ Throws ▫ finally • Program statements that you want to monitor for exceptions are contained within a try block. • If an exception occurs within the try block , it is thrown
  • 8.
    • Your codecan catch this using a catch block and handle them it in some rational manner. • System generated exceptions are automatically thrown by Java runtime system. • To manually throw the exceptions, use the keyword throw. • In some case, an exception that is thrown out of the method must be specified as such by a throws clause. • Any code that absolutely must be executed upon exiting from a try block is put in a finally block.
  • 9.
    Using try andcatch • These keywords work together; • you can’t have a try without a catch, or catch without a try try { // block of code to monitor for errors } catch (ExcepType1 exOb) { // handler for ExcepType1 } catch (ExcepType2 exOb) { // handler for ExcepType2 }...
  • 10.
    • Here, ExcepTypeis the type of exception that has occurred. • When an exception is thrown, it is caught by its corresponding catch statement, which then processes the exception. • As the general form shows, there can be more than one catch statement associated with a try. • The type of the exception determines which catch statement is executed. • When an exception is caught, exOb will receive its value. • Here is an important point: If no exception is thrown, then a try block ends normally, and all of its catch statements are bypassed. Execution resumes with the first statement following the last catch. • Thus, catch statements are executed only if an exception is thrown.
  • 11.
    A simple exceptionexample • An error to attempt to index an array beyond its boundaries. • When this occurs, the JVM throws an ArrayIndexOutOfBoundsException.
  • 12.
    • This programdisplays the following output: Before exception is generated. Index out-of-bounds! After catch statement. • the code that you want to monitor for errors is contained within a try block. • when an exception occurs the exception is thrown out of the try block and caught by the catch statement. • After the catch statement executes, program control continues with the statements following the catch. • it is the job of your exception handler to remedy the problem that caused the exception so that program execution can continue normally. • if no exception is thrown by a try block, no catch statements will be executed and program control resumes after the catch statement
  • 13.
    The consequences ofan Uncaught Exception • By having an exception handler, it prevents abnormal program termination. • If your program does not catch an exception, then it will be caught by the JVM. • JVM exception handler terminates the execution and displays a stack trace and error message.
  • 14.
    // This won'twork! class ExcTypeMismatch { public static void main(String args[]) { int nums[] = new int[4]; try { System.out.println("Before exception is generated."); // generate an index out-of-bounds exception nums[7] = 10; System.out.println("this won't be displayed"); } /* Can't catch an array boundary error with an ArithmeticException. */ catch (ArithmeticException exc) { // catch the exception System.out.println("Index out-of-bounds!"); } System.out.println("After catch statement."); } }
  • 16.
    Exceptions enable youto handle errors gracefully • By having an exception handler ,it enables your program to respond to an error and then continue running. • If a division by zero occurs, an ArithmeticException is generated. • In the following program, this exception us handled by reporting the error then continuing with the execution. • Thus attempting to divide by zero does not cause an abrupt run-time error resulting a termination of the program.
  • 18.
    • Makes anotherimportant point, once an exception has been handled, it is removed for the system. • In program , each pass through the loop enters the try block new, any prior exception have been handled. • This enables your program to handle repeated errors.
  • 19.
    Using multiple catchstatements • We can associate more than one catch statement with a try. • Each catch must catch a different type of exception. • Program that catch both array boundary and divide by zero errors
  • 22.
    Catching subclass exceptions •A catch clause for a superclass will also match any of its subclasses. • Superclass of all exceptions is Throwable , to catch all possible exceptions. • If you want to catch exceptions of both superclass type and a subclass type put the subclass first in the catch sequence. • If you don’t then the superclass catch will also catch all derived classes.
  • 23.
    • Putting thesuper class first causes unreachable code to be created, since the subclass catch clause can never execute. • In java, unreachable code is an error.
  • 25.
  • 26.
    Nested Try blocks •One try block can be nested within another. • An exception generated within inner try block that is not caught by the catch block associated with the try propagated to the outer try block • Ex: ArrayIndecOutOfBoundException is not caught by the inner catch , but the outer catch
  • 29.
    Throwing an exception •It is possible to throw an exception by using throw statement. • General statement is: ▫ throw exceptObj; • Here the exceptObj should be an object of exception class derived from Throwable. • An example that illustrates the throw statement by manually throwing an ArithmeticException
  • 31.
    Rethrowing an exception •An exception caught by one catch statement can be rethrown so that it can be caught by an outer catch. • It allows multiple handlers access to the exception. • When you rethrow an exception, it will not be recaught by the same catch statement. • It will propagate to the next catch statement.
  • 33.
    class RethrowDemo { publicstatic void main(String args[]) { try { Rethrow.genException(); } catch(ArrayIndexOutOfBoundsException exc) { // recatch exception System.out.println("Fatal error – " + "program terminated."); } } }
  • 34.
    Closer look atThrowable class
  • 35.
    Using finally • Whenyou want to define a block of code that will execute when a try/catch block is left. • A method that has opened a file or a network connection that needs to be closed. • To specify a block of code to execute when a try/catch block is exited, included a finally block at the end of try/catch sequence. • General form of try/catch that includes finally is as shown below.
  • 37.
    • The finallyblock will be executed whenever execution leaves a try/catch block, no matter what condition causes it. • i.e. whether try block ends normally or because of an exception, last code that will be executed is defined by finally. • Example of using the concept of finally
  • 39.
    class FinallyDemo { publicstatic void main(String args[]) { for(int i=0; i < 3; i++) { UseFinally.genException(i); System.out.println(); } } }
  • 40.
    • Here isthe output produced by the program. Receiving 0 Can't divide by Zero! Leaving try. Receiving 1 No matching element found. Leaving try. Receiving 2 Leaving try.
  • 41.
    Using throws • Ifa method generates an exception that it does not handle, it must declare that exception in throws clause. ret_type methname(param_list) throws excp_list{ //body } ▫ here excp_list is a comma sepearted list of exceptions that the method might throw outside of itself. ▫ When performing keyboard input, you should add the clause  throws java.IOException
  • 42.
    • An examplethat handles IOException. • It creates a method called prompt(), which displays a prompting message and then reads a character from the keyboard. • Since the input is being performed , an IOException might occur. • prompt() uses a throws() which means that the calling method must handle it. • The following example, the calling method is main(), and deals with the error.
  • 44.
    Java built-in exceptions •Inside standard package java.lang , Java defines several exception classes. • There are two kinds of exceptions • Checked exceptions ▫ The exceptions defined by java.lang that must be included in a methods throws list if that method can generate one of these exceptions and does not handle it itself. • Unchecked exceptions ▫ if the compiler does not check to see if a method handles or throws these exceptions.
  • 47.
    Creating Exception subclasses •Creating an exception is easy • Just define a subclass of exception class. • This subclass need not implement anything, it inherits those methods provided by Throwable class. • Exception called NonIntResultException , which is generated when the result of dividing two integer values produce a result with a fractional and override of the toString() method, allowing the description to be printed using println() method.