Exception Handling, Mutithreading

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 6

Exception Handling

Eg: class Exc2 { public static void main(String args[]) { int d, a; try { d = 0; a = 42 / d; System.out.println("This will not be printed."); } catch (ArithmeticException e) { System.out.println("Division by zero."); } System.out.println("After catch statement."); } } This program generates the following output: Division by zero. After catch statement. catch (ArithmeticException e) { System.out.println("Exception: " + e); } Exception: java.lang.ArithmeticException: / by zero

Multiple catch Clauses


In some cases, more than one exception could be raised by a single piece of code. To handle this type of situation, we can specify two or more catch clauses, each catching a different type of exception. When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. After one catch statement executes, the others are bypassed, and execution continues after the try/catch block. The following example traps two different exception types: class demo { public static void main (String args []) { int A[] = new int[5]; try { for (int c = 0; c <5; c++) { A[c] = c/ c;

} } catch (ArrayIndexOutOfBoundsException e) { System.out.println ("Array out of bound "); } catch (ArithmeticException e) { System.out.println ("Zero divide error"); } } } Output: Zero divide error Throwing an Exception We can throw an exception explicitly using the throw statement. Using the throw Statement It is possible for your program to throw an exception explicitly, using the throw statement. The general form of throw is shown here: throw ThrowableInstance; 1. The throw statement causes termination of the normal flow of control of the java code and prevents the execution of the subsequent statements. 2. The throw clause convey the control to the nearest catch block handling the type of exception object throws. 3. If no such catch block exists, the program terminates. class demo { public static void main (String args[ ]) { try { throw new IllegalStateException (); } catch (NullPointerException e) { System.out.println ("Not Caught by the catch block inside tdemo ()."); } catch(IllegalStateException e) { System.out.println("Exception Caught in:" + e); } } } Exception Caught in:java.lang.IllegalStateException Using the throws Statement The throws statement is used by a method to specify the types of exceptions the method throws. If a method is capable of raising an exception that it does not handle, the method must specify that the exception have to be handled by the calling method. A throws clause lists the types of exceptions that a method might throw. This is the general form of a method declaration that includes a throws clause:

type 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. class ThrowsDemo { static void throwOne() throws IllegalAccessException { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[]) { Try { throwOne(); } catch (IllegalAccessException e) { System.out.println("Caught " + e); }}} Here is the output generated by running this example program: inside throwOne caught java.lang.IllegalAccessException: demo

finally Block
finally creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute 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 of them before returning. The finally clause is optional. However, each try statement requires at least one catch or a finally clause. Example: public class demo { public static void main(String args[]) { try { System.out.println("Try Block before the error."); System.out.println(1/0); System.out.println("Try Block after the error."); } catch(java.lang.ArithmeticException e) { System.out.println("Catch Block"); System.out.println("A Stack Trace of the Error:"); e.printStackTrace(); System.out.println("The operation is not possible.");

} finally { System.out.println("Finally Block"); } System.out.println("demo is over"); } } Try Block before the error. Catch Block A Stack Trace of the Error: java.lang.ArithmeticException: / by zero at demo.main(demo.java:8) The operation is not possible. Finally Block demo is over Creating Threads Threads are implemented in the form of objects that contain method called run( ). It makes up the entire body of the thread and is the only method in which the thread behaviour can be implemented.

The run method should be invoked by an object of the concerned method. This can be achieved by creating the thread and initiating it with the help of another thread method called start( ). Stopping Threads Whenever we want to stop a thread from running further we may do so by stop( ) method aThread.stop( ); This statement causes the thread to move to the dead state. A thread will also move to the dead state automatically when it reaches to the end of statement. Blocking a Thread A thread can also be temporarily suspended or blocked from entering into the runnable and subsequently running state by using either of the following methods. Sleep ( ), suspend( ), wait( ) These methods cause the thread to go into the blocked state. The thread will return to the runnable state when the specified time is elapsed in the case of sleep( ), the resume( ) method is invoked in the case of suspend and the notify( ) method is called in the case of wait( ).

Synchronization
When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time. The process by which this is achieved is called synchronization .Key to synchronization is the concept of the monitor (also called a semaphore). A monitor is an object that is used as a mutually exclusive lock, or mutex. Only one thread can own a monitor at a given time. When a thread acquires a lock, it is said to have entered the monitor. All other threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor. These other threads are said to be waiting for the monitor. A thread that owns a monitor can reenter the same monitor if it so desires. Synchronization is easy in Java, because all objects have their own implicit monitor associated with them. To enter an object's monitor, just call a method that has been modified with the synchronized keyword. While a thread is inside a synchronized method, all other threads that try to call it (or any other synchronized method) on the same instance have to wait. To exit the monitor and relinquish control of the object to the next waiting thread, the owner of the monitor simply returns from the synchronized method.

Thread Life cycle:

1. New state After the construction of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive. 2. Runnable (Ready-to-run) state A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can come again to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor. 3. Running state A thread is in running state that means the thread is presently executing. There are numerous ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool. 4. Dead state A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again. 5. Blocked - A thread can enter in this state because of waiting the resources that are hold by another thread.

You might also like