UNIT V
Exception handling and multithreading - Concepts of exception handling, benefits of exception
handling, Termination or resumptive models, exception hierarchy, usage of try, catch, throw,
throws and finally, built in exceptions, creating own exception sub classes. Differences between
multi threading and multitasking, thread life cycle, creating threads, synchronizing threads,
daemon threads, thread groups.
Exception Handling in Java
• An exception is a run-time error. Exception can also be defined as an abnormal or
unexpected condition that’s occurs at run-time (when executing the program).
• The process of handling exceptions is known as Exception Handling.
•Exceptions can be generated by the Java run-time system or manually generated by the code
in the program.
•Exceptions generated by the Java run-time system are handled by the Java run-time itself.
•Manually created exceptions must be handled by the programmer.
•Java provides five keywords for exception handling. They are:
1) try
2) catch
3) throw
4) throws
5) finally
•try: Any statements that may raise an exception are included in the “try” block. Every “try”
block requires atleast one “catch” or “finally” block.
•catch: The exception handling code is provided in the “catch” block.
•throw: System-generated exceptions are thrown by the Java run-time system. To manually
throw an exception, use the keyword throw.
•throws: Any exception that is thrown out of a method must be specified as such by a throws
clause.
•finally: Any code that must be executed whether or not an exception occurs is written in the
“finally” block.
This is the general form of an exception-handling block:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
}
Here, ExceptionType is the type of exception that has occurred.
What is Try Block?
The try block contains a block of program statements within which an exception might occur. A
try block is always followed by a catch block, which handles the exception that occurs in
associated try block. A try block must followed by a Catch block or Finally block or both.
Syntax of try block
try{
//statements that may cause an exception
}
What is Catch Block?
A catch block must be associated with a try block. The corresponding catch block executes if an
exception of a particular type occurs within the try block. For example if an arithmetic
exception occurs in try block then the statements enclosed in catch block for arithmetic
exception executes.
Syntax of try catch in java
try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}
Flow of try catch block
1. If an exception occurs in try block then the control of execution is passed to the catch
block from try block. The exception is caught up by the corresponding catch block. A
single try block can have multiple catch statements associated with it, but each catch
block can be defined for only one exception class. The program can also contain nested
try-catch-finally blocks.
2. After the execution of all the try blocks, the code inside the finally block executes. It is
not mandatory to include a finally block at all, but if you do, it will run regardless of
whether an exception was thrown and handled by the try and catch blocks.
An example of Try catch in Java
class Example1 {
public static void main(String args[]) {
int num1, num2;
try {
// Try block to handle code that may cause exception
num1 = 0;
num2 = 62 / num1;
[Link]("Try block message");
} catch (ArithmeticException e) {
// This block is to catch divide-by-zero error
[Link]("Error: Don't divide a number by zero");
}
[Link]("I'm out of try-catch block in Java.");
}
}
Output:
Error: Don't divide a number by zero
I'm out of try-catch block in Java.
Multiple catch blocks in Java
1. A try block can have any number of catch blocks.
2. A catch block that is written for catching the class Exception can catch all other exceptions
Syntax:
catch(Exception e){
//This catch block catches all the exceptions
}
3. If multiple catch blocks are present in a program then the above mentioned catch block
should be placed at the last as per the exception handling best practices.
4. If the try block is not throwing any exception, the catch block will be completely ignored and
the program continues.
5. If the try block throws an exception, the appropriate catch block (if one exists) will catch it
–catch(ArithmeticException e) is a catch block that can catch ArithmeticException
–catch(NullPointerException e) is a catch block that can catch NullPointerException
6. All the statements in the catch block will be executed and then the program continues.
Example of Multiple catch blocks
class Example2{
public static void main(String args[]){
try{
int a[]=new int[7];
a[4]=30/0;
[Link]("First print statement in try block");
}
catch(ArithmeticException e){
[Link]("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
[Link]("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){
[Link]("Warning: Some Other exception");
}
[Link]("Out of try-catch block...");
}
}
Output:
Warning: ArithmeticException
Out of try-catch block...
In the above example there are multiple catch blocks and these catch blocks executes
sequentially when an exception occurs in try block. Which means if you put the last catch block
( catch(Exception e)) at the first place, just after try block then in case of any exception this
block will execute as it has the ability to handle all exceptions. This catch block should be placed
at the last to avoid such situations.
Nested try statements : Sometimes a situation may arise where a part of a block may cause
one error and the entire block itself may cause another error. In such cases, exception handlers
have to be nested.
The try statement can be nested.
That is, a try statement can be inside a block of another try.
Each time a try statement is entered, its corresponding catch block has to entered.
Syntax:
1. ....
2. try
3. {
4. statement 1;
5. statement 2;
6. try
7. {
8. statement 1;
9. statement 2;
10. }
11. catch(Exception e)
12. {
13. }
14. }
15. catch(Exception e)
16. {
17. }
18. ....
Java nested try example
Let's see a simple example of java nested try block.
1. class Excep6{
2. public static void main(String args[]){
3. try{
4. try{
5. [Link]("going to divide");
6. int b =39/0;
7. }catch(ArithmeticException e){[Link](e);}
8.
9. try{
10. int a[]=new int[5];
11. a[5]=4;
12. }catch(ArrayIndexOutOfBoundsException e){[Link](e);}
13.
14. [Link]("other statement);
15. }catch(Exception e){[Link]("handeled");}
16.
17. [Link]("normal flow.."); } }
Java throws keyword
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide
the exception handling code so that normal flow can be [Link] a method is using throws
clause along with few exceptions then this implicitly tells other methods that – “ If you call me,
you must handle these exceptions that I throw”.
Syntax of java throws
returntype method-name(parameter-list) throws exception-list
{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a method can throw.
Difference between throw and throws in Java
There are many differences between throw and throws keywords. A list of differences between
throw and throws are given below:
No. Throw throws
Java throw keyword is used to explicitly Java throws keyword is used to declare an
1)
throw an exception. exception.
Checked exception cannot be propagated Checked exception can be propagated with
2)
using throw only. throws.
3) Throw is followed by an instance. Throws is followed by class.
4) Throw is used within the method. Throws is used with the method signature.
You can declare multiple exceptions e.g.
5) You cannot throw multiple exceptions. public void method()throws
IOException,SQLException.
Java finally block is a block that is used to execute important code such as closing connection,
stream etc.
Java finally block is always executed whether exception is handled or not.
Java finally block must be followed by try or catch block.
Finally block in java can be used to put "cleanup" code such as closing a file, closing
connection etc.
Rule: For each try block there can be zero or more catch blocks, but only one finally block.
Note: The finally block will not be executed if program exits(either by calling [Link]() or
by causing a fatal error that causes the process to abort).
Syntax of Finally block
try
{
//statements that may cause an exception
}
finally
{
//statements to be executed
}
Cases when they finally block doesn’t execute
The circumstances that prevent execution of the code in a finally block are:
– The death of a Thread
– Using of the System. exit() method.
– Due to an exception arising in the finally block.
Example 2:Below example illustrates finally block execution when exception occurs in try block
but doesn’t get handled in catch block.
class Example2{
public static void main(String args[]){
try{
[Link]("First statement of try block");
int num=45/0;
[Link](num);
}
catch(ArrayIndexOutOfBoundsException e){
[Link]("ArrayIndexOutOfBoundsException");
}
finally{
[Link]("finally block");
}
[Link]("Out of try-catch-finally block");
}
}
Output:
First statement of try block
finally block
Exception in thread "main" [Link]: / by zero
at [Link]([Link])
Note: If you don't handle exception, before terminating the program, JVM executes finally
block(if any).
Difference between final, finally and finalize
There are many differences between final, finally and finalize. A list of differences between
final, finally and finalize are given below:
No. Final finally finalize
Final is used to apply restrictions on Finally is used to place Finalize is used to
class, method and variable. Final class important code, it will be perform clean up
1) can't be inherited, final method can't be executed whether processing just before
overridden and final variable value can't exception is handled or object is garbage
be changed. not. collected.
2) Final is a keyword. Finally is a block. Finalize is a method.
Java final example
1. class FinalExample{
2. public static void main(String[] args){
3. final int x=100;
4. x=200;//Compile Time Error
5. }}
Java finally example
1. class FinallyExample{
2. public static void main(String[] args){
3. try{
4. int x=300;
5. }catch(Exception e){[Link](e);}
6. finally{[Link]("finally block is executed");}
7. }}
Java finalize example
1. class FinalizeExample{
2. public void finalize(){[Link]("finalize called");}
3. public static void main(String[] args){
4. FinalizeExample f1=new FinalizeExample();
5. FinalizeExample f2=new FinalizeExample();
6. f1=null;
7. f2=null;
8. [Link]();
9. }}
Benefits of Exception Handling:
1. It is used to handle runtime errors
2. Exception handling allows us to control the normal flow of the program by using
exception handling in program.
3. It throws an exception whenever a calling method encounters an error providing that
the calling method takes care of that error.
4. It also gives us the scope of organizing and differentiating between different error types
using a separate block of codes. This is done with the help of try-catch blocks.
5. Separating Error-Handling Code from "Regular" Code: Exceptions provide the means to
separate the details of what to do when something out of the ordinary happens from
the main logic of a program. In traditional programming, error detection, reporting, and
handling often lead to confusing spaghetti code. Exceptions enable you to write the
main flow of your code and to deal with the exceptional cases elsewhere.
6. Propagating Errors Up the Call Stack: A second advantage of exceptions is the ability to
propagate error reporting up the call stack of methods.
7. Grouping and Differentiating Error Types: Because all exceptions thrown within a
program are objects, the grouping or categorizing of exceptions is a natural outcome of
the class hierarchy.
Termination or resumptive models:
There are two basic models in exception-handling theory.
In termination the error is so critical there’s no way to get back to where the exception
occurred. Whoever threw the exception decided that there was no way to salvage the
situation, and they don’t want to come back.
The alternative is called resumption. It means that the exception handler is expected to
do something to rectify the situation, and then the faulting method is retried, presuming
success the second time. If you want resumption, it means you still hope to continue
execution after the exception is handled.
In resumption a method call that want resumption-like behavior (i.e don’t throw an
exception all a method that fixes the problem.)
Alternatively, place your try block inside a while loop that keeps reentering the try block
until the result is satisfactory.
Operating systems that supported resumptive exception handling eventually ended up
using termination-like code and skipping resumption.
There are two basic models in exception-handling theory: termination and resumption.
In termination (which is what C++ supports), you assume the error is so critical that
there s no way to automatically resume execution at the point where the exception
occurred. In other words, whoever threw the exception decided there was no way to
salvage the situation, and they don t want to come back.
The alternative error-handling model is called resumption, first introduced with the PL/I
language in the 1960s.[2] Using resumption semantics means that the exception handler
is expected to do something to rectify the situation, and then the faulting code is
automatically retried, presuming success the second time. If you want resumption in C+
+, you must explicitly transfer execution back to the code where the error occurred,
usually by repeating the function call that sent you there in the first place. It is not
unusual to place your try block inside a while loop that keeps reentering the try block
until the result is satisfactory.
Historically, programmers using operating systems that supported resumptive exception
handling eventually ended up using termination-like code and skipping resumption.
Although resumption sounds attractive at first, it seems it isn t quite so useful in
practice. One reason may be the distance that can occur between the exception and its
handler. It is one thing to terminate to a handler that s far away, but to jump to that
handler and then back again may be too conceptually difficult for large systems where
the exception is generated from many points
Exception Hierarchy:
In Java, exception can be checked or unchecked. They both fit into a class hierarchy. The
following diagram shows Java Exception classes hierarchy.
Red colored are checked exceptions. Any checked exceptions that may be thrown in a method
must either be caught or declared in the method's throws clause. Checked exceptions must be
caught at compile time. Checked exceptions are so called because both the Java compiler and
the Java virtual machine check to make sure this rule is obeyed. Green colored are uncheck
exceptions. They are exceptions that are not expected to be recovered, such as null pointer,
divide by 0, etc.
Checked exceptions are checked at compile-time. It means if a method is throwing a checked
exception then it should handle the exception using try-catch block or it should declare the
exception using throws keyword, otherwise the program will give a compilation error. It is
named as checked exception because these exceptions are checked at Compile time.
Following are some Examples of Checked Exception in Java library:
IOException
SQLException
DataAccessException
ClassNotFoundException
InvocationTargetException
Unchecked exceptions are not checked at compile time. It means if your program is throwing an
unchecked exception and even if you didn’t handle/declare that exception, the program won’t
give a compilation error. Most of the times these exception occurs due to the bad data
provided by user during the user-program interaction. It is up to the programmer to judge the
conditions in advance, that can cause such exceptions and handle them appropriately. All
Unchecked exceptions are direct sub classes of RuntimeException class
Here are the few most frequently seen unchecked exceptions –
NullPointerException
ArrayIndexOutOfBoundsException
ArithmeticException
IllegalArgumentException
IllegalStateException
Java defines several exception classes inside the standard package [Link].
The most general of these exceptions are subclasses of the standard type RuntimeException.
Since [Link] is implicitly imported into all Java programs, most exceptions derived from
RuntimeException are automatically available.
Java defines several other types of exceptions that relate to its various class libraries. Following
is the list of Java Unchecked RuntimeException.
Java has lot of built-in exceptions. The list of important exceptions and their summary is shown
here. This list is included from the book Java, The Complete Reference, Eighth Edition.
The list of unchecked exceptions or the exception classes which extend from RuntimeException .
Exception Description
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a method.
Illegal monitor operation, such as waiting on an unlocked
IllegalMonitorStateException
thread.
IllegalStateException Environment or application is in incorrect state.
IllegalThreadStateException Requested operation not compatible with current thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric format.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
UnsupportedOperationException An unsupported operation was encountered.
Following is the list of Java Checked Exceptions Defined in [Link].
Exception Description
ClassNotFoundException Class not found.
Attempt to clone an object that does not implement the Cloneable
CloneNotSupportedException
interface.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class or interface.
InterruptedException One thread has been interrupted by another thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.