Exception handling

6
1 An Exception is… An unusual, often unpredictable event, detectable by software or hardware, that requires special processing An exception handler is a section of program code that is executed when a particular exception occurs.

Transcript of Exception handling

Page 1: Exception handling

1

An Exception is…

An unusual, often unpredictable event, detectable by software or hardware, that requires special processing

An exception handler is a section of program code

that is executed when a particular exception occurs.

Page 2: Exception handling

2

Why have exception handlers?

With no exception handler for an exception, your program ends at the point of the exception (with no user understandable data from the O/S)

With an exception handler, you can handle the unusual condition in an understandable way

Page 3: Exception handling

3

Try/Catch/Throw

Try: The block of code monitored for exceptions

Catch: The block of code following the try block handles an exception type

Throw: When an exception is detected, you throw an exception type

Page 4: Exception handling

4

The try-catch Statement

try Block (exception can be thrown within this block or any called functions)catch (FormalParameter1) Blockcatch (FormalParameter2)

TryCatchStatement

How one part of the program catches and processes the exception that another part of the program throws.

FormalParameterDataType VariableName

Page 5: Exception handling

5

Execution of try-catch

No statements throw

an exception

Statement following entire try-catch

statement

A statement throws

an exception

Exception Handler

Statements to deal with exception are executed

Control moves directly to exception handler

Page 6: Exception handling

6

O/S (Unix) or you can throw exceptions

O/S thrown examples No storage available for new request, divide by zero

User thrown exceptions Using the throw statement