Beruflich Dokumente
Kultur Dokumente
6COMPRG1
Examples:
-division by zero
-inputting invalid data
-array index out of bounds
try/catch/finally block
try
{ //statements }
catch(ExceptionClassName1 objRef1)
{ //exception handler code } …
catch(ExceptionClassNameN objRefN)
{ //exception handler code }
finally
{ //statements }
o Statements that might generate an exception are placed in the try block. It
might also contain statements that should not be executed if an exception
occurs.
o A catch block specifies the type of exception it can catch and contains an
exception handler.
o Any code in the finally block always executes, regardless of whether an
exception occurs, except when the program exits early by calling the
System.exit method.
o If no exception is thrown in a try block, all catch blocks associated with the try
block are ignored and program execution resumes after the last catch block.
o If an exception is thrown, in a try block, the remaining statements in the try
block are ignored. The program searches the catch blocks in the order in
which they appear after the try block and looks for an appropriate exception
handler.
o If the type of the thrown exception matches the parameter type in one of the
catch blocks, the code of that catch block executes and the remaining catch
blocks after this catch block are ignored.
o If there is a finally block after the last catch block,the finally block executes
regardless of whether an exception occurs.
catch block
catch (ArithmeticException aeRef)
{ //exception handler code }
This catch block catches an exception of type ArithmeticException. The identifier aeRef
is a reference variable of type ArithmeticException. aeRef contains the address of
the exception object, the exception object can be accessed through the variable
aeRef. It stores the detailed description of the thrown exception.
*the method toString may be used to retrieve the message containing the description of
the thrown exception.