Unit 4
Unit 4
• When an Exception occurs the normal flow of the program is disrupted and
the program/Application terminates abnormally,
• These exceptions cannot simply be ignored, the programmer should take care
of (handle) these exceptions.
• E.G. if you use FileReader class in your program to read data from a file, if
the file specified in its constructor doesn't exist,
then FileNotFoundException occurs, and the compiler prompts the
programmer to handle the exception.
• FileNotFoundException
• IOException
• ClassNotFoundException
2 Unchecked exceptions
• Errors are typically ignored in your code because you can rarely do anything
about an error.
• For example, if a stack overflow occurs, an error will arise. They are also
ignored at the time of compilation.
• OutOfMemoryError
This is the general form of an exception-handling block:
try {
----
---
} catch (ExceptionType1 exOb) {
-----
-----
}
try {
----
---
}
catch (ExceptionType1 exOb)
{
-----
-----
}
catch (ExceptionType2 exOb)
{
-----
-----
}
finally
{
-----
-----
}
// Java program to demonstrate ArithmeticException
class ArithmeticException_Demo
{
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
System.out.println ("Result = " + c);
} catch(ArithmeticException e) {
System.out.println ("Can't divide a number by 0“);
}
}
}
• Output :
• Can't divide a number by 0
public class ExcepTest {
public static void main(String args[]) {
try {
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
System.out.println(“1111");
System.out.println(“2222");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of try catch block");
}
}
Ouput
Exception thrown :java.lang.ArrayIndexOutOfBoundsException
Out of try catch block
• //Java program to demonstrate NullPointerException
class NullPointerDemo
{
public static void main(String args[])
{
try {
String a = null; //null value
System.out.println(a.charAt(0));
} catch(NullPointerException e) {
System.out.println("NullPointerException..“ );
}
}
• Output
NullPointerException
//Java program to demonstrate FileNotFoundException
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo {
try{
int a [ ]=new int[5];
a[5]=30/0;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
System.out.println("rest of the code");
}
}
Output
Arithmetic Exception occurs
rest of the code
• Java finally block
• 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 follows try or catch block.
• Syntax
try{
-----
----
}
catch(Exception e)
{
-----------
}
finally
{
--------
}
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){
System.out.println(e);
}
finally{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
• OUTPUT
• 5
• finally block is always executed
• rest of the code...
• throws keyword
• exceptions that a method can throw must be declared in the throws clause.
• The throws keyword is used as follows to list the exceptions that a method can
throw:
• Syntax
• throw exception;
• java provides us facility to create our own exceptions which are basically
derived classes of Exception.
• E.g.
• For example, imagine a situation in which a method throws an
ArithmeticException because of an attempt to divide by zero.
• To allow chained exceptions, two constructors and two methods were added
to Throwable.
• Throwable(Throwable causeExc)
• Throwable(String msg, Throwable causeExc)
• Introduction
• Definition :
thread is the smallest unit of dispatchable code.
OR a thread is a lightweight sub-process
• Advantages
• disadvantages:
• Complex debugging and testing processes.
• Overhead switching of context.
• Increased potential for deadlock occurrence.
• Increased difficulty level in writing a program.
• Unpredictable results.
• Thread Lifecycle
• Main Thread
• Main Thread
• When a Java program starts up, one thread begins running immediately.
• This is usually called the main thread of our program, because it is the one that
is executed when our program begins.
• Properties :
• It is the thread from which other “child” threads will be spawned.
• Often, it must be the last thread to finish execution because it performs
various shutdown actions.
public class Thread1 {
System.out.println("thread ="+th);
th.setName("Mythread");
System.out.println("thread after name change ="+th);
}
}
• thread =Thread[main,5,main]
• thread after name change =Thread[Mythread,5,main]
• threads are light-weight processes within a process.
Creating Thread:
1. Extending the Thread class
2. Implementing the Runnable Interface
• Thread 10 is running
• Thread 14 is running
• Thread 13 is running
• Thread 12 is running
• Thread 11 is running
• Thread 16 is running
• Thread 15 is running
• Thread 17 is running
• Thread creation by implementing the Runnable Interface
}
catch (Exception e)
{
System.out.println ("Exception is caught");
}
}
}
class Multithread
{
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i=0; i<8; i++)
{
Thread object = new Thread(new MultithreadingDemo());
object.start();
}
}}
• Thread Class vs Runnable Interface
1. If we extend the Thread class, our class cannot extend any other class
because Java doesn’t support multiple inheritance. But, if we implement the
Runnable interface, our class can still extend other base classes.
• public static int MIN_PRIORITY: This is minimum priority that a thread can
have. Value for this is 1.
• public static int NORM_PRIORITY: This is default priority of a thread if do not
explicitly define it. Value for this is 5.
• public static int MAX_PRIORITY: This is maximum priority of a thread. Value
for this is 10.
th.setPriority(10);
int q=th.getPriority();
System.out.println("Priority ="+q);
}
}
• Default Priority =5
• Priority =10
• Thread Methods
• Wait() -causes current thread to wait until another thread invokes the notify()
method or the notifyAll() method for this object.
• notify() It wakes up one single thread that called wait() on the same object.
• notifyAll().- wakes up all the threads that called wait() on the same object.
• Thread Synchronization
• situation where multiple threads try to access the same resources -erroneous data .
• synchronization method that only one thread can access the resource at a given point
of time.
• All synchronized blocks on the same object can only have one thread executing inside
them at a time.
• All other threads attempting to enter the synchronized block are blocked until the
thread inside the synchronized block exits the block.
• synchronized(sync_object) {
– // Access shared variables and other
– // shared resources
• }
class Sender{
class SyncDemo
{
public void send(String msg) {
public static void main(String args[]) {
System.out.println("Sending\t" + msg );
Sender snd = new Sender();
try{ Thread.sleep(1000); }
ThreadedSend S1 =
catch (Exception e) { new ThreadedSend( " Hi " , snd );
System.out.println("Thread interrupted."); ThreadedSend S2 =
} new ThreadedSend( " Bye " , snd );
System.out.println("\n" + msg + "Sent");
}} S1.start();
S2.start();
class ThreadedSend extends Thread{
private String msg;
try{
private Thread t;
S1.join();
Sender sender;
S2.join();
ThreadedSend(String m, Sender obj){ }
msg = m; catch(Exception e){
sender = obj; System.out.println("Interrupted");
} }
public void run(){ }
synchronized(sender) { }
sender.send(msg);
}
}}
• Output
• Sending Hi
• Hi Sent
• Sending Bye
• Bye Sent
• Inter-thread communication
• Inter-thread communication or Co-operation is all about allowing
synchronized threads to communicate with each other.
• Deadlock describes a situation where two or more threads are blocked forever,
waiting for each other.
• Deadlock occurs when multiple threads need the same locks but obtain them
in different order.
• The End