Vous êtes sur la page 1sur 20

Week # 5

Feb 25, 26

Exceptions & Exception Handling

Muhammad Sarmad Ali
Lecturer Software Engineering Dept.

Namal College An Associate College of University of Bradford Talagang Road, Mianwali, Pakistan

A program can be written assuming that nothing unusual or exceptional will happen:
User will provide the correct input Stack will never overflow File will be there to be opened Network connection will be established whenever needed and so on.

In reality, these assumptions will never always hold A good program is the one which can cater for exceptional situations so that it is robust and fault-tolerant

Heres what you might like to do:
open a text file read a line from the file

But heres what you might have to do:

try to open the file if the file doesnt exist, inform the user if it does, but you dont have permission to use the file, inform the user if youve the permission, but the file isnt a text file, inform the user now try to read a line from the file if you cant read a line, inform the user etc., etc.

All this error checking and handling of exceptional situations really gets in the way of developing a robust and usable software

What is an Exception?
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. Either your code or the Java Virtual Machine (JVM) signals when something unusual happens. The signaling process is called throwing an exception. Somewhere in your program, you can place code to handle the exception. This is called catching the exception.
SD-2, Spring - 2014

Writing Exception Handling Code

The exception handling mechanism in Java requires that code be segregated in following different blocks:
try block catch block finally block
try {
// statements that may throw an exception - try block is mendatory - At least one of the catch or finally block must immediately follow try block - finally must follow the catch block (if present)

} catch(ExceptionType e) {
// code to handle the exception

} finally {
// typically, code to avoid resource leakage

SD-2, Spring - 2012

try-catch rules
The first step in constructing an exception handler is to enclose the code that might throw an exception within a try block. A catch block handles the exception. This code executes when the try block detects the exception.
No code can be between the end of the try block and the beginning of the first catch block

If an exception occurs in a try block, the try block terminates immediately and program control transfers to the first catch block with a parameter type that matches the thrown exceptions type. After the execution of catch block, the program control does not return to the throw point in try block

try-catch Rules
If there are multiple matching catch blocks, then upon occurrence of exception, only the first one matching is executed. The rest are simply skipped.
try { // code that can throw exception } catch(SpecificExceptionType e){ // code that can throw exception } catch(MoreGenericExceptionType e){ // code that can throw exception } catch(MostGenericExceptionType e){ // code that can throw exception SD-2, Spring - 2014 }

The specific the catch block exception, the higher should its position be

finally block rules

Programs that obtain certain types of resources must return them to the system to avoid so-called resource leaks. Resource-release code typically is placed in a finally block. The finally block is optional. If its present, its placed after the last catch block.

The finally block will execute whether or not an exception is thrown in the corresponding try block
If an exception cannot be caught by one of the catch handlers, control proceeds to the finally block. Then the exception is passed to the next outer try block. If a catch block throws an exception, the finally block still executes. Then the exception is passed to the next outer try SD-2, Spring - 2014 8 block.

How it works?
After a method throws an exception, the Java runtime system attempts to find a method that contains a block of code (catch block) that can handle the exception. The search begins with the method in which the error occurred and proceeds through the method call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler.

SD-2, Spring - 2014

How it works?
If no catch block is found which can match the exception type, the runtime system reports an error with the stack trace and program may terminate.

SD-2, Spring - 2012


Uncaught Exception
An uncaught exception is the one for which there is no matching catch block

If a program has only one thread, an uncaught exception will cause the program to terminate.
If a program has multiple threads, an uncaught exception will terminate only the thread where the exception occurred.
In such programs, however, certain threads may rely on others, and if one thread terminates due to an uncaught exception, there may be adverse effects to the rest of the program
SD-2, Spring - 2014 11

Exception Hierarchy

SD-2, Spring - 2012


Class Throwable
The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the JVM or can be thrown by the Java throw statement. Only this class or one of its subclasses can be the argument type in a catch clause.

SD-2, Spring 2014


Catch or Specify Requirement

The code that might throw certain exceptions must be enclosed by either of the following:
A try statement that catches the exception. The try must provide a handler for the exception. A method that specifies that it can throw the exception. The method must provide a throws clause that lists the exception

Not all exceptions are subject to the Catch or Specify Requirement. Code that does not fulfil the Catch or Specify Requirement will not compile.

Categories of Exceptions
Two main categories
Checked exceptions Unchecked exception

Checked Exceptions
exceptional conditions that a well-written application must anticipate and recover from. For example, file system access, network access, etc. Checked exceptions are subject to the Catch or Specify Requirement

Categories of Exceptions
Unchecked Exceptions
exceptional conditions that are external to the application and that the application usually cannot anticipate or recover from. For example, hardware fault, VM error etc.

Runtime Exceptions
exceptional conditions that are internal to the application and that the application usually cannot anticipate or recover from. For example, logical or semantic errors, incorrect use of APIs

Errors and Runtime exceptions are not subject to the Catch or Specify Requirement

Categories of Exceptions

Need not be caught

Must be caught

i.e. writing catch handler is optional at compile-time


i.e. catch handler must be written at compiletime


Specifying the Exceptions Thrown by a Method

Sometimes, it's appropriate for a method to catch exceptions that can occur within it. However, there can be situations when it's better to let a method further up the call stack handle the exception. So if a method doesn't catch the checked exceptions that can occur within it, it must specify that it can throw these exceptions. A throws clause specifies a comma-separated list of exceptions that the method might throw, and appears after the methods parameter list and before the method body.
SD-2, Spring - 2014 18

Throwing Exceptions
Before you can catch an exception, some code somewhere must throw one. Any code can throw an exception, e.g.
Java runtime environment code from a package written by someone else such as the packages that come with the Java platform, or even your own code

Regardless of what throws the exception, it's always thrown with the throw statement.
SD-2, Spring - 2014 19

throw statement
All methods use the throw statement to throw an exception.
throw someThrowableObject;

The throw statement requires a single argument: a throwable object which is an instance of any subclass of the Throwable class.

SD-2, Spring - 2014