Exception handling

Post on 23-Jan-2017

22 views 0 download

Transcript of 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.

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

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

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

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

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