jump to navigation

Exceptions in Java July 28, 2005

Posted by Coolguy in J2SE.

Exception Handling:
An exception is an abnormal condition that arises in a code-sequence at runtime. A Java exception is an object that describes an exceptional condition that has occurred in a piece of code. When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error.That method may choose to handle the exception itself, or pass it on. Either way, at some time, the exception is caught and processed

Program statements that are monitored for exceptions are contained within a ‘try’ block. An exception thrown from the ‘try’ block is caught, using ‘catch’ block and handled in some rational way. System generated exceptions are automatically thrown by the Java runtime system. To manually throw an exception, use the keyword ‘throw’. Any exception that is thrown out of a method must be specified as such by a ‘throws’ clause. Any code that absolutely must be executed before a method returns is put in a ‘finally’ block.

Types of Exceptions:
All exception types are subclasses of the class Throwable.

Immediately below Throwable are two subclasses that partition exceptions into two distinct branches.

  • Exception
  • Error

Exception: This class is used for exceptional conditions that user programs should catch. This is also the class that you will subclass to create your own custom exception types. There is an important subclass of Exception, called RuntimeException. Exceptions of this type are automatically defined for the programs that you write, and include things such as division by zero and invalid array indexing.

Error: Defines exceptions that are not expected to be caught under normal circumstances by your programs. Exceptions of type Error are used by Java runtime system to indicate errors having to do with the runtime environment itself. Stack overflow is an example of such an error.

Uncaught exceptions:
Whenever an exception object is created and thrown by the runtime system, execution of the program stops, because once an exception has been thrown, it must be caught by an exception handler and dealt with immediately. If you do not supply any exception handlers, the exception is caught by the default handler provided by the Java runtime system.

The default handler displays a string describing the exception, prints a stack-trace from the point at which the exception has occurred, and terminates the program. The stack trace will always show the sequence of method invocations that led up to the error.

Effect on a thread:
If an exception is thrown and it is not handled, the execution jumps to the end of the current method. The exception then appears in the caller of that method, and execution jumps to the end of the calling method. This continues until execution reaches the top of the affected thread, at which point the thread dies

‘try’ and ‘catch’
Once an exception is thrown, the program control transfers out of the ‘try’ block into the ‘catch’ block. Catch block is not called, so execution never returns to the try block from catch. Once the catch statement has executed, program control continues with the next line in the program following the entire try/catch block.

The ‘finally’ clause creates a block of code that will be executed whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement matches the exception.
Any time a method is about to return to the caller from inside a try/catch block, via an uncaught exception or an explicit return statement, the ‘finally’ clause is also executed just before the method returns. This can be useful for closing file handles and freeing up any other resources that might have been allocated at the beginning of a method with the intent of disposing them before returning. The ‘finally’ clause is optional. However, each try statement requires at least one catch or a finally clause.

The circumstances that can prevent execution of finally block are :

  • The death of the thread.
  • The use of System.exit()
  • Interruption of power supply to the CPU.
  • An exception arising in the finally block itself.

The throw statement
It is possible for a program to throw an exception explicitly using the ‘throw’ statement (e.g. throw object;). The object to be thrown must of type Throwable or a subclass of it. Simple types such as int or char as well as non-Throwable classes, such as String or Object, cannot be used as exceptions.

The flow of execution stops immediately after the ‘throw’ statement; any subsequent statements are not executed. The nearest enclosing ‘try’ statement is inspected to see if it has a catch statement that matches the type of the exception. If it does find a match, control is transferred to that statement. If not, the next enclosing try statement is inspected and so on. If no matching catch block is found, then default exception handler halts the program and prints the stack trace.

The throws statement
If a method is capable of causing an exception that it does not handle itself, it must specify this behavior so that the callers of the method can guard themselves against that exception. It can be done by including a ‘throws’ clause in the method’s declaration. A throws clause lists the types of exceptions that a method might throw. This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses. All other exceptions that a method can throw must be declared in the ‘throws’ clause. If they are not, a compile time error will result. If a method declares that it throws more than one exception, class hierarchy of exceptions is important in the declaration – subclass coming before a super class.

Checked exceptions
The checked exceptions are problems that can arise in a correct program. These are concerned with difficulties with the environment such as user mistakes or I/O problems. Since these conditions can arise at anytime, a program must be able to handle and recover from them. The compiler checks whether a program has defined what is to be done when such conditions arise.

Exceptions and Overriding
A method which overrides a method in a super class can only be declared to throw checked exceptions of classes which were either declared to be thrown by the method in super class or which are subclasses of those exceptions declared in the method of super class.

Creating new Exception subclasses:
Although Java’s built-in exceptions handle most common errors, you may want to create your own exception types to handle situations specific to your applications. To do this, just define a subclass of Exception. Your subclasses do not need to implement anything actually – it is their existence in the type system that allows you to use them as exceptions.
The Exception class does not define any methods of its own. It does inherit those methods provided by Throwable. Thus all exceptions, including those that you create, have the methods defined by Throwable available to them. You may also wish to override one or more of these methods in exception classes that you create.

Methods defined in Throwable:
Throwable fillInStackTrace ()
String getLocalizedMessage ()
String getMessage ()
void printStackTrace ()
void printStackTrace (PrintStream stream)
void printStackTrace (Printwriter stream)
String toString ()



No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: