Exception Handling in Java:
• What is an Exception?
An exception is an “unwanted or unexpected event”, which occurs
during the execution of the program i.e, at run-time, that disrupts the
normal flow of the program’s instructions. When an exception occurs,
the execution of the program gets terminated.
• Why does an Exception occur?
An exception can occur due to several reasons like a Network
connection problem, Bad input provided by a user, Opening a non-
existing file in your program, etc.
Blocks & Keywords used for exception handling:
try:
The try block contains a set of statements where an exception can occur.
catch:
The catch block is used to handle the uncertain condition of a try block.
A try block is always followed by a catch block, which handles the
exception that occurs in the associated try block.
Nested try block:
Multiple catch blocks:
• A try block can be followed by multiple catch blocks.
• It means we can have any number of catch blocks after a single try
block.
• If an exception occurs in the guarded code(try block) the exception is
passed to the first catch block in the list.
• If the exception type matches with the first catch block it gets caught,
if not the exception is passed down to the next catch block.
• This continue until the exception is caught or falls through all catches.
Syntax:
Examples :
public class CatchDemo2
{
public static void main(String[] args)
{
try
{
int a[]=new int[10];
[Link](a[20]);
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception --> "+e);
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception --> "+e);
}
catch(Exception e)
{
[Link](e);
}
}
}
Throw, throws, finally keyword:
• Throw, throws, finally are the keywords in Java that are used in
exception handling.
• The throw keyword is used to throw an exception and throws is used
to declare the list of possible exceptions with the method signature.
• Whereas finally block is used to execute essential code, specially to
release the occupied resources.
Finally keyword:
• A finally keyword is used to create a block of code that follows a try
block.
• A finally block of code is always executed whether an exception has
occurred or not.
• Using a finally block, it lets you run any cleanup type statements that
you want to execute, no matter what happens in the protected code. A
finally block appears at the end of catch block.
Example finally Block:
In this example, we are using finally block along with try block.
This program throws an exception and due to exception, program terminates
its execution but see code written inside the finally block executed.
It is because of nature of finally block that guarantees to execute the code.
Class ExceptionTest
{
public static void main(String[] args)
{
int a[] = new int[2];
[Link]("out of try");
try
{
[Link]("Access invalid element"+ a[3]);
/* the above statement will throw ArrayIndexOutOfBoundException */
}
finally
{
[Link]("finally is always executed.");
}
}
}
Example : Finally Block
• finally block executes in all the scenario whether exception is caught
or not.
• In previous example, we use finally where exception was not caught,
but here exception is caught and finally is used with handler.
class Demo
{
public static void main(String[] args)
{
int a[] = new int[2];
try
{
[Link]("Access invalid element"+ a[3]);
/* the above statement will throw ArrayIndexOutOfBoundException */
}
catch(ArrayIndexOutOfBoundsException e) {
[Link]("Exception caught");
}
finally
{
[Link]("finally is always executed.");
}
}
}
Throw:
• The throw keyword is used to throw an exception explicitly.
• Only object of Throwable class or its sub classes can be thrown.
• Program execution stops on encountering throw statement, and the
closest catch statement is checked for matching type of exception.
Example throw Exception:
class Test
{
static void avg()
{
try
{
throw new ArithmeticException("demo");
}
catch(ArithmeticException e)
{
[Link]("Exception caught");
}
}
public static void main(String args[])
{
avg();
}
}
Output:
Exception caught
In the above example the avg() method throw an instance of ArithmeticException, which is
successfully handled using the catch statement and thus, the program prints the output
"Exception caught".
Throws:
• The throws keyword is used to declare the list of exception that a
method may throw during execution of program.
• Any method that is capable of causing exceptions must list all the
exceptions possible during its execution, so that anyone calling that
method gets a prior knowledge about which exceptions are to be
handled.
• A method can do so by using the throws keyword.
Example throws Keyword:
• Here, we have a method that can throw Arithmetic exception so we
mentioned that with the method declaration and catch that using the catch
handler in the main method.
class Test
{
static void check() throws ArithmeticException
{
[Link]("Inside check function");
throw new ArithmeticException("demo");
}
public static void main(String args[])
{
try
{
check();
}
catch(ArithmeticException e)
{
[Link]("caught" + e);
}
}
}
Java Thread:
Concepts:
Process and Thread are two basic units of execution.
[Link]
• A process is a self contained execution environment and it can be seen
as a program or application. However a program itself contains
multiple processes inside it. Java runtime environment runs as a single
process which contains different classes and programs as processes.
[Link]
• Thread can be called lightweight process. Thread requires less
resources to create and exists in the process, thread shares the process
resources.
• Java Thread Benefits
[Link] Threads are lightweight compared to processes, it takes less time
and resource to create a thread.
[Link] share their parent process data and code
[Link] switching between threads is usually less expensive than
between processes.
[Link] intercommunication is relatively easy than process
communication.
Thread Life Cycle in Java:
• Below diagram shows different states of thread life cycle in java. We
can create a thread in java and start it but how the thread states change
from Runnable to Running to Blocked depends on the OS
implementation of thread scheduler and java doesn’t have full control
on that.
[Link]
• When we create a new Thread object using new operator, thread state is
New Thread. At this point, thread is not alive and it’s a state internal to Java
programming.
[Link]
• When we call start() function on Thread object, it’s state is changed to
Runnable. The control is given to Thread scheduler to finish it’s execution.
Whether to run this thread instantly or keep it in runnable thread pool before
running, depends on the OS implementation of thread scheduler.
[Link]
• When thread is executing, it’s state is changed to Running. Thread scheduler
picks one of the thread from the runnable thread pool and change it’s state
to Running. Then CPU starts executing this thread. A thread can change
state to Runnable, Dead or Blocked from running state depends on time
slicing, thread completion of run() method or waiting for some resources.
[Link]/Waiting
• A thread can be waiting for other thread to finish using thread join or it
can be waiting for some resources to available. For example producer
consumer problem or waiter notifier implementation or IO resources,
then it’s state is changed to Waiting. Once the thread wait state is over,
it’s state is changed to Runnable and it’s moved back to runnable
thread pool.
[Link]
• Once the thread finished executing, it’s state is changed to Dead and
it’s considered to be not alive. Above are the different states of
thread. It’s good to know them and how thread changes it’s state.
That’s all for thread life cycle in java.
➢There are two ways to create a thread:
[Link] extending Thread class
[Link] implementing Runnable interface.
➢Thread class:
• Thread class provide constructors and methods to create and perform
operations on a [Link] class extends Object class and implements
Runnable interface.
➢Commonly used Constructors of Thread class:
• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r,String name)
• Java Thread Example by extending Thread class:
FileName: [Link]
• Java Thread Example by implementing Runnable interface:
FileName: [Link]
If you are not extending the Thread
class, your class object would not
be treated as a thread object. So you
need to explicitly create the Thread
class object. We are passing the
object of your class that implements
Runnable so that your class run()
method may execute.
• Using the Thread Class: Thread(String Name)
We can directly use the Thread class to spawn new threads using the
constructors defined above.
FileName: [Link]
• Using the Thread Class: Thread(Runnable r, String name)
Observe the following program.
FileName: [Link]