0% found this document useful (0 votes)
37 views56 pages

Unit 4

Unit 4 covers exception handling and multithreading in Java. It discusses the different types of exceptions like checked exceptions, unchecked exceptions, and errors. It explains how to handle exceptions using try, catch, throw, throws and finally keywords. Finally blocks ensure code is always executed even if an exception occurs. The document also discusses creating custom exceptions and chained exceptions in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views56 pages

Unit 4

Unit 4 covers exception handling and multithreading in Java. It discusses the different types of exceptions like checked exceptions, unchecked exceptions, and errors. It explains how to handle exceptions using try, catch, throw, throws and finally keywords. Finally blocks ensure code is always executed even if an exception occurs. The document also discusses creating custom exceptions and chained exceptions in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

Unit 4

Exception Handling &


Multithreading
• Introduction
• an exception (or exceptional event) is a problem that arises during the
execution of a program.

• When an Exception occurs the normal flow of the program is disrupted and
the program/Application terminates abnormally,

• When an exceptional event occurs in Java, an exception is said to be thrown.

• A Java exception is an object that describes an exceptional (that is, error)


condition
• Java exception handling is managed via five keywords: try, catch, throw,
throws, and finally
• The code that’s responsible for doing something about the exception is called
an exception handler, and it catches the thrown exception.
• All exception types are subclasses of the built-in class Throwable.
Types of exception
• Checked exceptions
• A checked exception is an exception that is checked by the compiler at
compilation-time, these are also called as compile time exceptions.

• 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

• An unchecked exception is an exception that occurs at the time of execution.


These are also called as Runtime Exceptions.
• Runtime exceptions are ignored at the time of compilation.
• E.g. if you have declared an array of size 5 in your program, and trying to call
the 6th element of the array then
an ArrayIndexOutOfBoundsExceptionexception occurs.
• NullPointerException
• ArithmeticException

• public class Unchecked_Demo {


public static void main(String args[]) {
int num[] = {1, 2, 3, 4};
System.out.println(num[5]);
}
}
• errors −
• These are not exceptions at all, but problems that arise beyond the control of
the user or the programmer.

• 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.

• Virtual Machine Error

• 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 {

public static void main(String args[]) {


try {
File file = new File("E://file.txt"); // Following file does not exist
FileReader fr = new FileReader(file);
}
catch (FileNotFoundException e)
{
System.out.println("File does not exist");
}
}
}
• Output:
File does not exist
Nested try Statement
try{
try{
------
----
}
catch( Exception e)
{
------
-----
}
}
catch(Exception e)
{
-----
-----
}
public class MultipleCatchBlock1 {

public static void main(String[] args) {

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

• throws keyword is used for handling checked exceptions .


• throws is used If a method is capable of causing an exception that it does not
handle,

• 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

void myFunction() throws MyException1, MyException2 {

// code for the method here


}
class ThrowExample {
void myMethod(int num) throws IOException
{
if(num==1)
throw new IOException("IOException Occurred");
else
System.out.println(“Exception not thrown”);
}
}
public class Example1{
public static void main(String args[]){
try{
ThrowExample obj=new ThrowExample();
obj.myMethod(1);
}catch(Exception ex){
System.out.println(ex);
}
}
}
Output : java.io.IOException: IOException Occurred
• The throw keyword in Java is used to explicitly throw an exception from a
method or any block of code.

• We can throw either checked or unchecked exception.

• The throw keyword is mainly used to throw custom exceptions.

• The syntax of java throw keyword is given below

• throw exception;

• E.g throw new IOException("sorry device error”);


• User-defined Custom Exception in Java / creating own exceptions in java

• java provides us facility to create our own exceptions which are basically
derived classes of Exception.

• We can create our own exception by extending Exception class


class MyException extends Exception
{
public MyException(String s)
{
super(s);
}
}

public class Main


{
public static void main(String args[])
{
try {
throw new MyException(“My OWN Exception");
}
catch (MyException ex) {
System.out.println("Caught");
System.out.println(ex.getMessage());
}
} Output:
} Caught
My OWN Exception
• Built in Exceptions
• Chained Exceptions
• The chained exception feature allows you to associate another exception with
an exception. This second exception describes the cause of the first 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)

• The chained exception methods supported by Throwable are getCause( ) and


initCause( ).
• Throwable getCause( )
• Throwable initCause(Throwable causeExc)
class ChainExcDemo {
static void demoproc() {
NullPointerException e = new NullPointerException("top layer");
e.initCause(new ArithmeticException("cause"));
throw e;
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Caught: " + e);
System.out.println("Original cause: " + e.getCause());
}
}
}
output
Caught: java.lang.NullPointerException: top layer
Original cause: java.lang.ArithmeticException: cause
• Multithreaded Programming

• Introduction

• two distinct types of multitasking:


• process-based
• thread-based.

• A multithreaded program contains two or more parts that can run


concurrently.

• Definition :
thread is the smallest unit of dispatchable code.
OR a thread is a lightweight sub-process
• Advantages

• Enhanced performance by decreased development time.


• Improvised GUI responsiveness.
• Simultaneous and parallelized occurrence of tasks
• Better utilization of resources
• Decreased cost of maintenance
• Better use of CPU resource

• 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 {

public static void main(String[] args) {


Thread th=Thread.currentThread();

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 creation by extending the Thread class

We create a class that extends the java.lang.Thread class.


This class overrides the run() method available in the Thread class.
A thread begins its life inside run() method.

call start() method to start the execution of a thread. .

Start() invokes the run() method on the Thread object.


class Mythread extends Thread{
public void run() {
for (int i=0;i<5;i++) {
System.out.println(i);
}
}
}
public class Simple {
public static void main(String []a) {
Mythread mt=new Mythread();
mt.start();
}
}
class MultithreadingDemo extends Thread {
public void run() {
try{
System.out.println ("Thread " + Thread.currentThread().getId() + " is
running");
} catch (Exception e) {
System.out.println ("Exception is caught");
}
}
}
public class Multithread {
public static void main(String[] args ) {
int n = 8; // Number of threads
for (int i=0; i<8; i++) {
MultithreadingDemo object = new MultithreadingDemo ();
object. start();
}
}}
• Output

• 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

We create a new class which implements java.lang.Runnable interface and


override run() method.
• Then we instantiate a Thread object and call start() method on this object.
class MultithreadingDemo implements Runnable
{
public void run()
{
try
{
System.out.println ("Thread " + Thread.currentThread().getId() + " is running");

}
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.

2. We can achieve basic functionality of a thread by extending Thread class


because it provides some inbuilt methods like yield(), interrupt() etc. that are
not available in Runnable interface.
• Thread priority
• Accepted value of priority for a thread is in range of 1 to 10. There are 3 static
variables defined in Thread class for priority.

• 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.

• public final int getPriority():


• java.lang.Thread.getPriority() method returns priority of given thread.
• public final void setPriority(int newPriority): java.lang.Thread.setPriority()
method changes the priority of thread to the value newPriority.
• This method throws IllegalArgumentException if value of parameter
newPriority goes beyond minimum(1) and maximum(10) limit.
public class Priority {
public static void main(String[] args) {
Thread th=Thread.currentThread();
int p=th.getPriority();
System.out.println("Default Priority ="+p);

th.setPriority(10);
int q=th.getPriority();
System.out.println("Priority ="+q);
}
}

• Default Priority =5
• Priority =10
• Thread Methods

• int getPriority() This method Returns this thread's priority.

• boolean isAlive() This method tests if this thread is alive.

• void setName(String name)


– This method changes the name of this thread to be equal to the argument name.

• void setPriority(int newPriority)


– This method changes the priority of this thread.

• static void sleep(long millis)


– This method causes the currently executing thread to sleep (temporarily cease execution) for the
specified number of milliseconds.

• void start() This method causes this thread to begin execution;


• The Object class in java contains three final methods that allows threads to
communicate about the lock status of a resource.

• These methods are wait(), notify() and notifyAll().

• 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.

• threads are synchronized in java using synchronized blocks.


• Synchronized keyword is used .

• 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.

• Inter-thread communication is a mechanism in which a thread is paused


running in its critical section and another thread is allowed to enter (or lock) in
the same critical section to be executed.

• It is implemented by following methods of Object class:


• Why wait(), notify() and notifyAll() methods are defined in Object class not
Thread class?
• It is because they are related to lock and object has a lock.
• Thread Deadlock

• 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

You might also like