comp 249 programming methodology chapter 9 – exception handling dr. aiman hanna department of...

41
Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal, Canada These slides has been extracted, modified and updated from original slides of Absolute Java 3 rd Edition by Savitch; which has originally been prepared by Rose Williams of Binghamton University. Absolute Java is published by Pearson Education / Addison-Wesley. Copyright © 2007 Pearson Addison-Wesley Copyright © 2010-2013 Aiman Hanna

Upload: darrell-thomerson

Post on 15-Jan-2016

224 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Comp 249 Programming Methodology Chapter 9 – Exception Handling

Dr. Aiman HannaDepartment of Computer Science & Software Engineering

Concordia University, Montreal, Canada

These slides has been extracted, modified and updated from original slides of Absolute Java 3 rd Edition by Savitch; which has originally been prepared by Rose Williams of Binghamton University. Absolute Java is published by

Pearson Education / Addison-Wesley.

Copyright © 2007 Pearson Addison-WesleyCopyright © 2010-2013 Aiman Hanna

All rights reserved

Page 2: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Introduction to Introduction to Exception HandlingException Handling

Sometimes the best outcome can be Sometimes the best outcome can be when nothing unusual happenswhen nothing unusual happens

However, the case where However, the case where exceptional things happen must also exceptional things happen must also be prepared forbe prepared for Java exception handling facilities are Java exception handling facilities are

used when the invocation of a method used when the invocation of a method may cause something exceptional to may cause something exceptional to occur occur

9-2

Page 3: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Introduction to Introduction to Exception HandlingException Handling

Java library software (or programmer-Java library software (or programmer-defined code) provides a mechanism that defined code) provides a mechanism that signals when something unusual happenssignals when something unusual happens This is called This is called throwing an exceptionthrowing an exception

In another place in the program, the In another place in the program, the programmer must provide code that deals programmer must provide code that deals with the exceptional casewith the exceptional case This is called This is called handling the exceptionhandling the exception

9-3

Page 4: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

try-throw-catchtry-throw-catch MechanismMechanism

The basic way of handling exceptions in Java The basic way of handling exceptions in Java consists of the consists of the try-throw-catchtry-throw-catch trio trio

The The trytry block contains the code for the basic block contains the code for the basic algorithmalgorithm It tells what to do when everything goes smoothlyIt tells what to do when everything goes smoothly It can also contain code that throws an exception It can also contain code that throws an exception

if something unusual happensif something unusual happens

trytry{{ CodeThatMayThrowAnExceptionCodeThatMayThrowAnException}}

9-4

Page 5: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

try-throw-catchtry-throw-catch MechanismMechanism

If something goes wrong within the If something goes wrong within the trytry block, block, execution of the block is stopped and an exception is execution of the block is stopped and an exception is thrownthrown The thrown exception is always an object of some exception The thrown exception is always an object of some exception

classclass

A A throwthrow statement would look like that: statement would look like that:throwthrow new new ExceptionClassNameExceptionClassName((PossiblySomeArgumentsPossiblySomeArguments);); The execution of a The execution of a throwthrow statement is called statement is called throwing an throwing an

exceptionexception

Normally, following the exception throwing, the flow of Normally, following the exception throwing, the flow of control is transferred to another portion of code control is transferred to another portion of code known as the known as the catchcatch block block

9-5

Page 6: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

try-throw-catchtry-throw-catch MechanismMechanism

When an exception is thrown, the When an exception is thrown, the catchcatch block begins executionblock begins execution The The catchcatch block has one parameter, which block has one parameter, which

is the object thrown by the exceptionis the object thrown by the exceptioncatch(catch(Exception eException e)){{ ExceptionHandlingCodeExceptionHandlingCode}}

Note: The identifier Note: The identifier ee is often used by is often used by convention, but any non-keyword identifier convention, but any non-keyword identifier can be usedcan be used

9-6

Page 7: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

try-throw-catchtry-throw-catch MechanismMechanism

The execution of the The execution of the catchcatch block is called block is called catching the exceptioncatching the exception, or , or handling the handling the exceptionexception Whenever an exception is thrown, it should Whenever an exception is thrown, it should

ultimately be handled (or caught) by some ultimately be handled (or caught) by some catchcatch blockblock

If no exception occurs, nothing is If no exception occurs, nothing is thrown and the thrown and the catchcatch block is skipped block is skipped

See ExceptionHandling1.javaSee ExceptionHandling1.javaSee ExceptionHandling2.javaSee ExceptionHandling2.javaSee ExceptionHandling3.javaSee ExceptionHandling3.java

9-7

Page 8: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Exception ClassesException Classes There are more exception classes than just the There are more exception classes than just the

single class single class ExceptionException New exception classes can also be defined like any New exception classes can also be defined like any

other classother class

All predefined exception classes have the All predefined exception classes have the following two properties:following two properties: There is a constructor that takes a single argument of There is a constructor that takes a single argument of

type type StringString The class has an accessor method The class has an accessor method getMessagegetMessage that that

returns the string given as an argument to the returns the string given as an argument to the constructor when the exception object was createdconstructor when the exception object was created

All programmer-defined classes All programmer-defined classes shouldshould have have the above two propertiesthe above two properties

9-8

Page 9: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Exception Classes from Standard Exception Classes from Standard PackagesPackages

Numerous predefined exception classes are Numerous predefined exception classes are included in the standard packages that included in the standard packages that come with Javacome with Java For example:For example:

IOExceptionIOExceptionNoSuchMethodExceptionNoSuchMethodExceptionFileNotFoundExceptionFileNotFoundException

Many exception classes must be imported in Many exception classes must be imported in order to use themorder to use themimport java.io.IOException;import java.io.IOException;

The class The class ExceptionException is in the is in the java.langjava.lang package, and so requires no package, and so requires no importimport statement statement

9-9

Page 10: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Exception Classes from Standard Exception Classes from Standard PackagesPackages

The predefined exception class The predefined exception class ExceptionException is the root class for all exceptionsis the root class for all exceptions

Every exception class is a derived, or Every exception class is a derived, or descendent, class of the class descendent, class of the class ExceptionException

Although the Although the ExceptionException class can be used class can be used directly in a class or program, it is most often directly in a class or program, it is most often used to define a derived classused to define a derived class

9-10

Page 11: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Defining Exception Defining Exception ClassesClasses

A A throwthrow statement can throw an exception statement can throw an exception object of any exception classobject of any exception class

Instead of using a predefined class, Instead of using a predefined class, programmers can define their own programmers can define their own exception classesexception classes These can be tailored to carry the precise These can be tailored to carry the precise

kinds of information needed in the kinds of information needed in the catchcatch block block Different types of exception can be defined to Different types of exception can be defined to

identify different exceptional situationsidentify different exceptional situations

9-11

Page 12: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Defining Exception Defining Exception ClassesClasses

Every exception class to be defined must be a Every exception class to be defined must be a derived class of some already defined derived class of some already defined exception classexception class It can be a derived class of any exception class in It can be a derived class of any exception class in

the standard Java libraries, or of any programmer the standard Java libraries, or of any programmer defined exception classdefined exception class

Constructors are the most important Constructors are the most important members to define in an exception classmembers to define in an exception class They must behave appropriately with respect to the They must behave appropriately with respect to the

variables and methods inherited from the base variables and methods inherited from the base classclass

Often, there are no other members, except those Often, there are no other members, except those inherited from the base classinherited from the base class

The following exception class performs these The following exception class performs these basic tasks onlybasic tasks only

9-12

Page 13: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

An Example of a Programmer-An Example of a Programmer-Defined Exception ClassDefined Exception Class

9-13

See ExceptionHandling4.java

Page 14: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Tip: An Exception Class Can Tip: An Exception Class Can Carry a Message of Any Type: Carry a Message of Any Type:

int Messageint Message An exception class constructor can be An exception class constructor can be

defined that takes an argument of defined that takes an argument of another typeanother type

It would stores its value in an instance It would stores its value in an instance variablevariable

It would need to define accessor methods It would need to define accessor methods for this instance variablefor this instance variable

9-14

Page 15: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

An Exception Class with an An Exception Class with an intint Message Message

9-15

Page 16: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Throwing an Exception in a Throwing an Exception in a MethodMethod

Sometimes it makes sense to throw an exception Sometimes it makes sense to throw an exception in a method, but not catch it in the same methodin a method, but not catch it in the same method Some programs that use a method should just end if an Some programs that use a method should just end if an

exception is thrown, and other programs should do exception is thrown, and other programs should do something elsesomething else

In such cases, the program using the method should In such cases, the program using the method should enclose the method invocation in a enclose the method invocation in a trytry block, and catch block, and catch the exception in a the exception in a catchcatch block that follows block that follows

In this case, the method itself would not include In this case, the method itself would not include trytry and and catchcatch blocks blocks

In such a case, the method must provide a In such a case, the method must provide a warning warning This warning is called a This warning is called a throwsthrows clause clause

9-16

Page 17: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Declaring Exceptions in a Declaring Exceptions in a throwsthrows ClauseClause

The process of including an exception The process of including an exception class in a throws clause is called class in a throws clause is called declaring the exceptiondeclaring the exception

throws throws AnExceptionAnException //throws clause//throws clause

The following states that an invocation of The following states that an invocation of aMethodaMethod could throw could throw AnExceptionAnException

public void aMethod() throws AnExceptionpublic void aMethod() throws AnException

See ExceptionHandling5.javaSee ExceptionHandling5.java9-17

Page 18: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Declaring Exceptions in a Declaring Exceptions in a throwsthrows ClauseClause

If a method can throw more than one If a method can throw more than one type of exception, then the exception type of exception, then the exception types are separated by commastypes are separated by commaspublic void aMethod()public void aMethod() throwsthrows

AnException, AnotherExceptionAnException, AnotherException If a method throws an exception and the catch clause If a method throws an exception and the catch clause

is inside the method, then throwing the exception is inside the method, then throwing the exception does not terminate the method (i.e. executes the does not terminate the method (i.e. executes the catch and what follows it, if any)catch and what follows it, if any)

However if the catch is not inside the method, then However if the catch is not inside the method, then throwing the exception ends the method immediatelythrowing the exception ends the method immediately

9-18

Page 19: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

The Catch or Declare The Catch or Declare RuleRule

Most ordinary exceptions that might be Most ordinary exceptions that might be thrown within a method must be thrown within a method must be accounted for in one of two ways:accounted for in one of two ways:

1.1. The code that can throw an exception is The code that can throw an exception is placed within a placed within a trytry block, and the possible block, and the possible exception is caught in a exception is caught in a catchcatch block within block within the same methodthe same method

2.2. The possible exception can be declared at the The possible exception can be declared at the start of the method definition by placing the start of the method definition by placing the exception class name in a exception class name in a throwsthrows clause clause

9-19

Page 20: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

The Catch or Declare The Catch or Declare RuleRule

The first technique handles an exception in a The first technique handles an exception in a catchcatch blockblock

The second technique is a way to shift the exception The second technique is a way to shift the exception handling responsibility to the method that invoked handling responsibility to the method that invoked the exception throwing methodthe exception throwing method

The invoking method must handle the exception, The invoking method must handle the exception, unless it too uses the same technique to "pass the unless it too uses the same technique to "pass the buck“buck“

Ultimately, every exception that is thrown should Ultimately, every exception that is thrown should eventually be caught by a eventually be caught by a catchcatch block in some block in some method that does not just declare the exception class method that does not just declare the exception class in a in a throwsthrows clause clause

9-20

Page 21: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

The Catch or Declare The Catch or Declare RuleRule

In any one method, both techniques can be In any one method, both techniques can be mixedmixed Some exceptions may be caught, and others may be Some exceptions may be caught, and others may be

declared in a declared in a throwsthrows clause clause

However, these techniques must be used However, these techniques must be used consistently with a given exceptionconsistently with a given exception If an exception is not declared, then it must be handled If an exception is not declared, then it must be handled

within the methodwithin the method If an exception is declared, then the responsibility for If an exception is declared, then the responsibility for

handling it is shifted to some other calling methodhandling it is shifted to some other calling method

Note that if a method definition encloses an invocation Note that if a method definition encloses an invocation of a second method, and the second method can throw of a second method, and the second method can throw an exception and does not catch it, then the first an exception and does not catch it, then the first method must catch or declare itmethod must catch or declare it

9-21

Page 22: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Multiple Multiple catchcatch Blocks Blocks

A A trytry block can potentially throw any number block can potentially throw any number of exception values, and they can be of of exception values, and they can be of different typesdifferent types In any one execution of a In any one execution of a trytry block, at most one block, at most one

exception can be thrown (since a throw statement exception can be thrown (since a throw statement ends the execution of the ends the execution of the trytry block) block)

Different types of exceptions can be caught by Different types of exceptions can be caught by placing more than one placing more than one catchcatch block after a block after a trytry blockblock Any number of Any number of catchcatch blocks can be included, but blocks can be included, but

they must be placed in the correct orderthey must be placed in the correct order

9-22

Page 23: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Pitfall: Catch the More Specific Pitfall: Catch the More Specific Exception FirstException First

When catching multiple exceptions, the When catching multiple exceptions, the order of the order of the catchcatch blocks is important blocks is important

When an exception is thrown in a When an exception is thrown in a trytry block, block, the the catchcatch blocks are examined in order blocks are examined in order

The first one that matches the type of the The first one that matches the type of the exception thrown is the one that is executedexception thrown is the one that is executed

See ExceptionHandling6.javaSee ExceptionHandling6.java

9-23

Page 24: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Pitfall: Catch the More Specific Pitfall: Catch the More Specific Exception FirstException First

Example: Example:

catch (Exception e)catch (Exception e){ . . . }{ . . . }catch (NegativeNumberException e)catch (NegativeNumberException e){ . . . }{ . . . }

Because a Because a NegativeNumberExceptionNegativeNumberException is a type of is a type of ExceptionException, all , all NegativeNumberExceptionsNegativeNumberExceptions will be will be caught by the first caught by the first catchcatch block before ever block before ever reaching the second blockreaching the second block The catch block for The catch block for NegativeNumberExceptionNegativeNumberException will never will never

be used!be used! For the correct ordering, simply reverse the two For the correct ordering, simply reverse the two

blocksblocks

9-24

Page 25: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Checked and Unchecked Checked and Unchecked ExceptionsExceptions

Exceptions that are subject to the catch or Exceptions that are subject to the catch or declare rule are called declare rule are called checkedchecked exceptionsexceptions The compiler checksThe compiler checks to see if they are accounted for to see if they are accounted for

with either a catch block or a throws clausewith either a catch block or a throws clause The classes The classes ThrowableThrowable, which is the superclass of all , which is the superclass of all

errors and exceptions in Java, errors and exceptions in Java, ExceptionException, and all , and all descendants of the class descendants of the class ExceptionException are checked are checked exceptionsexceptions

All other exceptions are All other exceptions are uncheckedunchecked exceptions exceptions The class The class ErrorError and all its descendant classes and all its descendant classes

are called are called error classes error classes Error classes are Error classes are notnot subject to the Catch or Declare subject to the Catch or Declare

RuleRule

9-25

Page 26: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Exceptions to the Catch or Declare Exceptions to the Catch or Declare RuleRule

Checked exceptions must follow the Checked exceptions must follow the Catch or Declare RuleCatch or Declare Rule Programs in which these exceptions can Programs in which these exceptions can

be thrown will not compile until they are be thrown will not compile until they are handled properlyhandled properly

Unchecked exceptions are exempt Unchecked exceptions are exempt from the Catch or Declare Rulefrom the Catch or Declare Rule Programs in which these exceptions are Programs in which these exceptions are

thrown simply need to be corrected, as thrown simply need to be corrected, as they result from some sort of errorthey result from some sort of error

9-26

Page 27: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Hierarchy of Throwable Hierarchy of Throwable ObjectsObjects

9-27

Page 28: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

The The throwsthrows Clause in Derived Clause in Derived ClassesClasses

When a method in a derived class is When a method in a derived class is overridden, it should have the same overridden, it should have the same exception classes listed in its exception classes listed in its throwsthrows clause that it had in the base classclause that it had in the base class Or it should have a subset of themOr it should have a subset of them

A derived class may not add any A derived class may not add any exceptions to the exceptions to the throwsthrows clause clause But it can delete someBut it can delete some

9-28

Page 29: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

What Happens If an Exception is What Happens If an Exception is Never Caught?Never Caught?

If every method up to and including the main If every method up to and including the main method simply includes a method simply includes a throwsthrows clause for an clause for an exception, that exception may be thrown but exception, that exception may be thrown but never caughtnever caught In a GUI program (i.e., a program with a windowing In a GUI program (i.e., a program with a windowing

interface), nothing happens - but the user may be left in interface), nothing happens - but the user may be left in an unexplained situation, and the program may no an unexplained situation, and the program may no longer be reliablelonger be reliable

In non-GUI programs, this causes the program to In non-GUI programs, this causes the program to terminate with an error message giving the name of the terminate with an error message giving the name of the exception classexception class

Every well-written program should eventually Every well-written program should eventually catch every exception by a catch every exception by a catchcatch block in some block in some methodmethod

9-29

Page 30: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

When to Use ExceptionsWhen to Use Exceptions Exceptions should be reserved for Exceptions should be reserved for

situations where a method encounters situations where a method encounters an an unusual or unexpected case that cannot unusual or unexpected case that cannot be handled easily in some other waybe handled easily in some other way

When exception handling must be used, When exception handling must be used, some basic guidelines should be followed:some basic guidelines should be followed: Include Include throwthrow statements and list the statements and list the

exception classes in a exception classes in a throwsthrows clause within a clause within a method definitionmethod definition

Place the Place the trytry and and catchcatch blocks in a different blocks in a different methodmethod

9-30

Page 31: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Event Driven Event Driven ProgrammingProgramming

Exception handling is an example of a Exception handling is an example of a programming methodology known as programming methodology known as event-driven programmingevent-driven programming

When using event-driven programming, When using event-driven programming, objects are defined so that they send objects are defined so that they send events to other objects that handle the events to other objects that handle the eventsevents An event is an object alsoAn event is an object also Sending an event is called Sending an event is called firing an eventfiring an event

9-31

Page 32: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Event Driven Event Driven ProgrammingProgramming

In exception handling, the event In exception handling, the event objects are the exception objectsobjects are the exception objects They are fired (thrown) by an object They are fired (thrown) by an object

when the object invokes a method that when the object invokes a method that throws the exceptionthrows the exception

An exception event is sent to a An exception event is sent to a catchcatch block, where it is handledblock, where it is handled

9-32

Page 33: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Pitfall: Nested Pitfall: Nested try-catchtry-catch BlocksBlocks

It is possible to place a It is possible to place a trytry block and its following block and its following catch blocks inside a larger catch blocks inside a larger trytry block, or inside a block, or inside a larger larger catchcatch block block

If a set of If a set of try-catchtry-catch blocks are placed inside a larger blocks are placed inside a larger catchcatch block, different names must be used for the block, different names must be used for the catchcatch block block parameters in the inner and outer blocks, just like any other parameters in the inner and outer blocks, just like any other set of nested blocksset of nested blocks

If a set of If a set of try-catchtry-catch blocks are placed inside a larger blocks are placed inside a larger trytry block, and an exception is thrown in the inner block, and an exception is thrown in the inner trytry block that is block that is not caught, then the exception is thrown to the outer not caught, then the exception is thrown to the outer trytry block block for processing, and may be caught in one of its for processing, and may be caught in one of its catchcatch blocks blocks

See ExceptionHandling7.javaSee ExceptionHandling7.java

9-33

Page 34: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

The The finallyfinally Block Block The The finallyfinally block contains code to be block contains code to be

executed whether or not an exception is executed whether or not an exception is thrown in a thrown in a trytry block block If it is used, a If it is used, a finallyfinally block is placed after a block is placed after a trytry

block and its following block and its following catchcatch blocks blockstrytry{ . . . }{ . . . }catch(ExceptionClass1 e)catch(ExceptionClass1 e){ . . . }{ . . . } . . . . . . catch(ExceptionClassN e)catch(ExceptionClassN e){ . . . }{ . . . }finallyfinally{{ CodeToBeExecutedInAllCasesCodeToBeExecutedInAllCases}}

See ExceptionHandling8.javaSee ExceptionHandling8.java9-34

Page 35: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

The The finallyfinally Block Block If the If the try-catch-finallytry-catch-finally blocks are inside a method blocks are inside a method

definition, there are three possibilities when the code definition, there are three possibilities when the code is run:is run:

1.1. The The trytry block runs to the end, no exception is thrown, and block runs to the end, no exception is thrown, and the the finallyfinally block is executed block is executed

2.2. An exception is thrown in the An exception is thrown in the trytry block, caught in one of the block, caught in one of the catchcatch blocks, and the blocks, and the finallyfinally block is executed block is executed

3.3. An exception is thrown in the An exception is thrown in the trytry block, there is no matching block, there is no matching catchcatch block in the method, the block in the method, the finallyfinally block is executed, block is executed, and then the method invocation ends and the exception and then the method invocation ends and the exception object is thrown to the enclosing methodobject is thrown to the enclosing method

Note: Of course, if the execution of any code that proceeds the finally block Note: Of course, if the execution of any code that proceeds the finally block results in flow control being driven away (i.e execute System.exit(0);), the results in flow control being driven away (i.e execute System.exit(0);), the finally block will not executefinally block will not execute

9-35

Page 36: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Rethrowing an ExceptionRethrowing an Exception

A A catchcatch block can contain code that block can contain code that throws an exceptionthrows an exception Sometimes it is useful to catch an Sometimes it is useful to catch an

exception and then, depending on the exception and then, depending on the string produced by string produced by getMessagegetMessage (or (or perhaps something else), throw the perhaps something else), throw the same or a different exception for same or a different exception for handling further up the chain of handling further up the chain of exception handling blocksexception handling blocks

See ExceptionHandling9.javaSee ExceptionHandling9.java9-36

Page 37: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

The The AssertionErrorAssertionError Class Class When a program contains an assertion When a program contains an assertion

check, and the assertion check fails, an check, and the assertion check fails, an object of the class object of the class AssertionErrorAssertionError is is thrownthrown This causes the program to end with an error This causes the program to end with an error

messagemessage

The class The class AssertionErrorAssertionError is derived from is derived from the class the class ErrorError, and therefore is an , and therefore is an unchecked exceptionunchecked exception In order to prevent the program from ending, In order to prevent the program from ending,

it could be handled, but this is not requiredit could be handled, but this is not required

9-37

Page 38: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Tip: Exception Tip: Exception Controlled LoopsControlled Loops

Sometimes it is better to simply loop through an Sometimes it is better to simply loop through an action again when an exception is thrown, as follows:action again when an exception is thrown, as follows:

boolean done = false;boolean done = false;while (! done)while (! done){{ trytry {{ CodeThatMayThrowAnExceptionCodeThatMayThrowAnException done = true;done = true; }} catch (SomeExceptionClass e)catch (SomeExceptionClass e) {{ SomeMoreCodeSomeMoreCode }}}}

9-38

Page 39: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Exception Handling with the Exception Handling with the ScannerScanner Class Class

The The nextIntnextInt method of the method of the ScannerScanner class class can be used to read can be used to read intint values from the values from the keyboardkeyboard

However, if a user enters something other However, if a user enters something other than a well-formed than a well-formed intint value, an value, an InputMismatchExceptionInputMismatchException will be thrown will be thrown Unless this exception is caught, the program Unless this exception is caught, the program

will end with an error messagewill end with an error message If the exception is caught, the If the exception is caught, the catchcatch block can block can

give code for some alternative action, such as give code for some alternative action, such as asking the user to reenter the inputasking the user to reenter the input

See ExceptionHandling10.javaSee ExceptionHandling10.java9-39

Page 40: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

The The InputMismatchExceptionInputMismatchException The The InputMismatchExceptionInputMismatchException is in is in

the standard Java package the standard Java package java.utiljava.util A program that refers to it must use an A program that refers to it must use an importimport statement, such as the following: statement, such as the following:import java.util.InputMismatchException;import java.util.InputMismatchException;

It is a descendent class of It is a descendent class of RuntimeExceptionRuntimeException Therefore, it is an unchecked exception Therefore, it is an unchecked exception

and does not have to be caught in a and does not have to be caught in a catchcatch block or declared in a block or declared in a throwsthrows clause clause

However, catching it in a However, catching it in a catchcatch block is block is allowed, and can sometimes be usefulallowed, and can sometimes be useful

9-40

Page 41: Comp 249 Programming Methodology Chapter 9 – Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

ArrayIndexOutOfBoundsExceptionArrayIndexOutOfBoundsException

An An ArrayIndexOutOfBoundsExceptionArrayIndexOutOfBoundsException is thrown is thrown whenever a program attempts to use an array whenever a program attempts to use an array index that is out of bounds index that is out of bounds This normally causes the program to endThis normally causes the program to end

Like all other descendents of the class Like all other descendents of the class RuntimeExceptionRuntimeException, it is an unchecked exception, it is an unchecked exception There is no requirement to handle itThere is no requirement to handle it

When this exception is thrown, it is an indication When this exception is thrown, it is an indication that the program contains an errorthat the program contains an error Instead of attempting to handle the exception, the Instead of attempting to handle the exception, the

program should simply be fixedprogram should simply be fixed

9-41