50
Chapter2-Exception Handling Unit 3

Java-Unit 3- Chap2 exception handling

Embed Size (px)

Citation preview

Page 1: Java-Unit 3- Chap2 exception handling

Chapter2-Exception HandlingUnit 3

Page 2: Java-Unit 3- Chap2 exception handling

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

Page 3: Java-Unit 3- Chap2 exception handling

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.

Page 4: Java-Unit 3- Chap2 exception handling

• 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.

Page 5: Java-Unit 3- Chap2 exception handling

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.

Page 6: Java-Unit 3- Chap2 exception handling

• 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.

Page 7: Java-Unit 3- Chap2 exception handling

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

Page 8: Java-Unit 3- Chap2 exception handling

• 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.

Page 9: Java-Unit 3- Chap2 exception handling

Using try and catch• These keywords work together;• you can’t have a try without a catch, or catch

without a trytry {// block of code to monitor for errors}catch (ExcepType1 exOb) {// handler for ExcepType1}catch (ExcepType2 exOb) {// handler for ExcepType2}...

Page 10: Java-Unit 3- Chap2 exception handling

• 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.

Page 11: Java-Unit 3- Chap2 exception handling

A simple exception example• An error to attempt to index an array beyond its

boundaries.• When this occurs, the JVM throws an

ArrayIndexOutOfBoundsException.

Page 12: Java-Unit 3- Chap2 exception handling

• 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

Page 13: Java-Unit 3- Chap2 exception handling

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.

Page 14: Java-Unit 3- Chap2 exception handling

// 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 exceptionnums[7] = 10;System.out.println("this won't be displayed");

}/* Can't catch an array boundary error with anArithmeticException. */catch (ArithmeticException exc) {

// catch the exceptionSystem.out.println("Index out-of-bounds!");

}System.out.println("After catch statement."); }}

Page 15: Java-Unit 3- Chap2 exception handling
Page 16: Java-Unit 3- Chap2 exception handling

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.

Page 17: Java-Unit 3- Chap2 exception handling
Page 18: Java-Unit 3- Chap2 exception handling

• 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.

Page 19: Java-Unit 3- Chap2 exception handling

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

Page 20: Java-Unit 3- Chap2 exception handling
Page 21: Java-Unit 3- Chap2 exception handling
Page 22: Java-Unit 3- Chap2 exception handling

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.

Page 23: Java-Unit 3- Chap2 exception handling

• 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.

Page 24: Java-Unit 3- Chap2 exception handling
Page 25: Java-Unit 3- Chap2 exception handling

output

Page 26: Java-Unit 3- Chap2 exception handling

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

Page 27: Java-Unit 3- Chap2 exception handling
Page 28: Java-Unit 3- Chap2 exception handling
Page 29: Java-Unit 3- Chap2 exception handling

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

Page 30: Java-Unit 3- Chap2 exception handling
Page 31: Java-Unit 3- Chap2 exception handling

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.

Page 32: Java-Unit 3- Chap2 exception handling
Page 33: Java-Unit 3- Chap2 exception handling

class RethrowDemo {public static void main(String args[]) {try {Rethrow.genException();}catch(ArrayIndexOutOfBoundsException exc) {// recatch exceptionSystem.out.println("Fatal error – " +"program terminated."); }}

}

Page 34: Java-Unit 3- Chap2 exception handling

Closer look at Throwable class

Page 35: Java-Unit 3- Chap2 exception handling

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.

Page 36: Java-Unit 3- Chap2 exception handling
Page 37: Java-Unit 3- Chap2 exception handling

• 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

Page 38: Java-Unit 3- Chap2 exception handling
Page 39: Java-Unit 3- Chap2 exception handling

class FinallyDemo {public static void main(String args[]) {

for(int i=0; i < 3; i++) {UseFinally.genException(i);System.out.println();

}}

}

Page 40: Java-Unit 3- Chap2 exception handling

• Here is the output produced by the program.Receiving 0Can't divide by Zero!Leaving try.

Receiving 1No matching element found.Leaving try.

Receiving 2Leaving try.

Page 41: Java-Unit 3- Chap2 exception handling

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

Page 42: Java-Unit 3- Chap2 exception handling

• 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.

Page 43: Java-Unit 3- Chap2 exception handling
Page 44: Java-Unit 3- Chap2 exception handling

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.

Page 45: Java-Unit 3- Chap2 exception handling
Page 46: Java-Unit 3- Chap2 exception handling
Page 47: Java-Unit 3- Chap2 exception handling

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.

Page 48: Java-Unit 3- Chap2 exception handling
Page 49: Java-Unit 3- Chap2 exception handling
Page 50: Java-Unit 3- Chap2 exception handling

End of chapter 1 unit 3

Thank you !