UNIT4_Exception Handling & Multithreading
UNIT4_Exception Handling & Multithreading
PROGRAMMING
UNIT IV:EXCEPTION HANDLING &
MULTITHREADING
Types of errors
Introduction Errors and Exception:
• The Exception Handling in Java is one of the powerful mechanism to
handle the runtime errors so that the normal flow of the application
can be maintained.
• Error may produce
The core advantage of exception handling is to maintain the normal flow of the
application.
Exception Hierarchy
• All exception and error types are subclasses of class Throwable, which is
the base class of the hierarchy.
• Immediately below Throwable, are two subclasses that partition
exceptions into two distinct branches.
1. Exception Class :
• One branch is headed by Exception. This class is used for exceptional
conditions that user programs should catch.
• Ex.NullPointerException is an example of such an exception.
2. Error Class :
• Another branch, Error is used by the Java run-time system(JVM) to
indicate errors having to do with the run-time environment itself(JRE).
• Ex.StackOverflowError is an example of such an error.
Exception Hierarchy
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. An error
is considered as the unchecked exception.
However, according to Oracle, there are three types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error
1. Checked Exceptions:
• Compile-time Check: Checked exceptions are checked at compile-time
by the Java compiler. This means that the compiler ensures that these
exceptions are either caught or declared in the method signature using the
throws keyword.
• Examples: Examples of checked exceptions include IOException,
SQLException, ParseException, etc.
• Forced Handling: Checked exceptions enforce explicit handling, either
by catching them or declaring them to be thrown. This helps in improving
code reliability and robustness.
• Recovery Possible: Checked exceptions typically represent recoverable
conditions, such as file not found or database connection failure, where
the application may take corrective action.
2. Unchecked Exceptions (Runtime Exceptions):
• Not Checked at Compile-time: Unlike checked exceptions, unchecked
exceptions are not checked at compile-time. This means that the compiler
does not enforce handling of unchecked exceptions.
• Examples: Examples of unchecked exceptions include
NullPointerException, ArrayIndexOutOfBoundsException,
ArithmeticException, etc.
• Runtime Errors: Unchecked exceptions often represent programming
errors or unexpected conditions during runtime, such as null references or
array index out of bounds.
• Optional Handling: Handling of unchecked exceptions is optional. While
it's good practice to handle them for robustness, it's not mandatory.
3. Errors:
• Not Meant for Handling: Errors represent exceptional conditions that are
typically beyond the control of the application and are not meant to be
caught or handled by application code.
• Examples: Examples of errors include OutOfMemoryError,
StackOverflowError, NoClassDefFoundError, etc.
• Critical Conditions: Errors usually indicate critical conditions, such as
JVM failures or system resource exhaustion, where the application cannot
recover.
Exception Handling Mechanism:
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
Example 2:
class TryCatchEx
{ Output:
public static void main(String args[]) Caught an exception: / by Zero
{ End of the program
try
{
int a=10,b=0;
int x = a / b; // Arithmetic exception
System.out.println(“Result=” +x);
}
catch(ArithmeticException e)
{
System.out.println(“Caught an exception:” + e);
}
System.out.println(“End of the program”); //This line will execute
}
}
Example 3:
Here, we handle the exception using the parent class exception.
public class TryCatchExample4
{
public static void main(String[] args)
{
try
{
int data=50/0; //may throw exception
}
catch(Exception e)
{ Output:
System.out.println(e); java.lang.ArithmeticExcep
} tion: / by zero
System.out.println("rest of the code"); rest of the cod
}
}
Example 4:
Output:
public class TryCatchExample9 java.lang.ArrayIndexOutOfBounds
{ Exception: 10
public static void main(String[] args) rest of the code
{
try
{
int arr[]= {1,3,5,7};
System.out.println(arr[10]); //may throw exception
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Multiple catch blocks
• A try block can be followed by one or more catch blocks.
• Each catch block must contain a different exception handler. So, if
you have to perform different tasks at the occurrence of different
exceptions, use java multi-catch block.
• At a time only one exception occurs and at a time only one catch
block is executed.
• All catch blocks must be ordered from most specific to most general,
i.e. catch for ArithmeticException must come before catch for
Exception.
Example:
public class MultipleCatchBlock1
{
public static void main(String[] args)
{
try
{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent 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.
• If you don't handle exception, before terminating the program, JVM
executes finally block(if any).
• Finally block in java can be used to put "cleanup" code such as
closing a file, closing connection etc.
• For each try block there can be zero or more catch blocks, but only
one finally block.
Use:
1. closing file , record set
2. closing the connection with database
3. releasing system resources
4. releasing fonts
5. Terminating network connections, printer connection etc.
We can use finally in this two way.
Syntax:2
Syntax:1
try
try {
{ ………..
………….. }
catch(…….)
}
{
finally …………….
{ }
……………... catch (…….)
} {
}
finally
{
}
Example: finally
class finallyEx {
{
System.out.println(" try catch is finished.");
public static void main(String[] args)
{ }
try }
{ }
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} Output:
catch (Exception e) Something wrong.
{ try catch is finished.
System.out.println("Something wrong.");
}
Case 1: When an exception does not occur
class TestFinallyBlock
{
public static void main(String args[])
{
try
{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
Case 1: When an exception does not occur
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of phe code...");
}
}
Case 2: When an exception occurr but not handled by the catch block
public class TestFinallyBlock1
{
public static void main(String args[])
{
try
{
System.out.println("Inside the try block");
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
Case 2: When an exception occurr but not handled by the catch block
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
throw
• The "throw" keyword in Java is used to explicitly throw an exception.
• It disrupts the normal flow of the program by transferring control to the
nearest catch block that can handle the thrown exception.
• When an exception occurs within a method, the method creates an
exception object and throws it using the "throw" keyword.
• throw keyword throws a new exception.
• An object of class that extends throwable can be thrown and caught.
• Throwable ->Exception -> MyException
• The flow of execution stops immediately after the throw statement ;
public class TestThrow
{
public static void checkNum(int num)
{
if (num < 1)
{
throw new ArithmeticException("Number is negative");
}
else
{
System.out.println("Square is " + (num*num));
}
}
public static void main(String[] args)
{
TestThrow obj = new TestThrow();
obj.checkNum(-3);
System.out.println("Rest of the code..");
}
}
throws
• On the other hand, the "throws" clause is used in method signatures to
indicate that the method may throw certain types of exceptions during its
execution.
• It doesn't actually throw the exception; instead, it declares that the
method may throw exceptions of specified types, thereby alerting the
caller to handle them appropriately.
public class TestThrows
{
public static int divideNum(int m, int n) throws ArithmeticException
{
int div = m / n;
return div;
}
public static void main(String[] args)
{
TestThrows obj = new TestThrows();
try
{
System.out.println(obj.divideNum(45, 0));
}
catch (ArithmeticException e)
{
System.out.println("\nNumber cannot be divided by 0");
}
System.out.println("Rest of the code..");
}
}
Java throw and throws Example
public class TestThrowAndThrows
{
static void method() throws ArithmeticException
{
System.out.println("Inside the method()");
throw new ArithmeticException("throwing ArithmeticException");
}
public static void main(String args[])
{
try
{
method();
}
Java throw and throws Example
catch(ArithmeticException e)
{
System.out.println("caught in main() method");
}
}
}
Java Custom Exception
• In Java, we can create our own exceptions that are derived classes of the
Exception class. Creating our own Exception is known as custom
exception or user-defined exception.
• Basically, Java custom exceptions are used to customize the exception
according to user need.
• Using the custom exception, we can have your own exception and
message. Here, we have passed a string to the constructor of superclass
i.e. Exception class that can be obtained using getMessage() method on
the object we have created.
• In order to create custom exception, we need to extend Exception class
that belongs to java.lang package.
Java Custom Exception
Syntax
Here is the syntax to create a custom class in Java -
class MyException extends Exception
{
}
public class TestCustomException1
{
static void validate (int age) throws InvalidAgeException
{
if(age < 18)
{
throw new InvalidAgeException("age is not valid to vote");
}
else
{
System.out.println("welcome to vote");
}
}
public static void main(String args[])
{
try
{
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");
System.out.println("Exception occured: " + ex);
}
System.out.println("rest of the code...");
}
}
class InvalidAgeException extends Exception
{
InvalidAgeException(String str)
{
super(str);
}
}
Common java Exceptions
SR Exception Type Cause of Exception
NO.
1 ArithmeticException Caused by math error such as divide by zero
2 ArrayIndexOutOfBoundsException Caused by bad array indexes
3 ArrayStoreException Caused when a program tries to store the wrong type of data in
an array
4 FileNotFoundException Caused by an attempt to access a nonexistent file
5 IOException Caused by general I/O failures, such as inability to read from a
file
6 NullPointerException Caused by referencing a null object
7 NumberFormatException Caused when a conversion between strings and number fails
8 OutOfMemoryException Caused when there’s not enough memory to allocate a new
object
9 SecurityException Caused when an applet tries to perform an action not allowed
by the browser’s security
Uses of exceptions
The advantages of Exception Handling in Java are as follows:
1. Provision to Complete Program Execution
2. Easy Identification of Program Code and Error-Handling Code
3. Propagation of Errors
4. Meaningful Error Reporting
5. Identifying Error Types
Concept of Multithreading
• Multithreading is a conceptual programming paradigm where a program
(or process) is divided into two or more subprograms(or process),which
can be implemented at the same time in parallel.
• Threads in java are subprograms of main application program and share
the same memory space.
• Multithreading is similar to dividing a task into subtasks and assigning
them to different people for execution independently and simultaneously,
to achieve a single desire.
• We use multithreading than multiprocessing because threads use a shared
memory area.
• It is mostly used in games, animation, etc.
Advantages of Java Multithreading
1. It doesn't block the user because threads are independent and you can
perform multiple operations at the same time.
2. You can perform many operations together, so it saves time.
3. Threads are independent, so it doesn't affect other threads if an
exception occurs in a single thread.
What is a Process?
• A process can be defined as an instance of a program that is being
executed by your computer's CPU.
• When you run a program, the operating system creates a new process and
assigns it a unique process ID. This process receives a set of resources,
such as memory space and CPU time, to execute the program.
• A process is an active program, i.e., a program that is under execution.
• It is more than the program code, as it includes the program counter,
process stack, registers, program code etc. Compared to this, the program
code is only the text section.
Examples of Processes
• Browser Application: When you open your favourite web browser, an
individual process is started for the application. Each tab you open might
be a separate process or thread, depending on the browser setup.
• Music Player: Let's say you're listening to music while browsing. Your
music player runs as a separate process, having its own resources and
operating independently from your browser.
• Database Queries: If you're running a server, each request to your
database could be a new process.
• File System Operations: Operations like copying or moving files
involve processes on an operating system level.
Advantages of Java Multithreading
Concept of thread
• Definition: “A thread is a lightweight sub process, the smallest unit of
processing.”
• It is a separate path of execution.
• Threads are independent.
• If exception occurs in one thread, it doesn't affect other threads. It uses a
shared memory area.
• We can increase the speed of application using thread.
• Thread is executed inside the process as shown in figure below:
Examples of Threads
• Browser Tabs: Most modern web browsers use threads. Each tab you
open in your browser runs a separate thread, allowing it to perform tasks
like loading a webpage or a video independently of the other tabs.
• Text Editors: When using a text editor, it often has to perform multiple
tasks like spell checking, auto-saving, and responding to the user's inputs.
These tasks can be executed as separate threads.
• Video Games: In video games, separate threads can be used for different
tasks such as loading graphics, accepting user input, and running game
logic. This allows for smooth gaming experience.
• Server Requests: Server-based applications often use threads to handle
multiple requests simultaneously. Each request can be processed as a
separate thread.
• A thread is executed along with its several operations within a single process
as shown in figure below:
Single Process Thread 1
Operation 1
Operation 2
…….
Operation N
• A multithreaded programs contain two or more threads that can run concurrently.
• Threads share the same data and code.
Life cycle of a thread
During the life time of a thread ,there are many states it can enter, They are:
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
1) New born state :
• Whenever a new thread is created, it is always in the new state.
• At this time we can scheduled it for running, using start() method or kill it using stop
() method.
• If we attempt to use any other method at this stage, an exception will be thrown.
2) Runnable state
• The thread is ready for execution and is waiting for the availability of the processor.
• The threads has joined waiting queue for execution.
• If all threads have equal priority, then they are given time slots for execution in round
robin fashion. i.e. first-come, first serve manner.
• This process of assigning time to thread is known as time-slicing.
• If we want a thread to relinquish(leave) control to another thread of equal priority
before its turn comes, then yield( ) method is used.
3) Running state
• The processor has given its time to the thread for its execution.
• The thread runs until it relinquishes control on its own or it is preempted by a higher
priority thread.
• A running thread may change its state to another state in one of the following
situations.
1) When It has been suspended using suspend( ) method.
2) It has been made to sleep( ).
3) When it has been told to wait until some events occurs.