0% found this document useful (0 votes)
23 views90 pages

Java Exception Handling Explained

The document provides an overview of Exception Handling in Java, explaining its importance in maintaining the normal flow of applications during runtime errors. It details the types of exceptions, including checked and unchecked exceptions, and introduces the keywords used for handling exceptions such as try, catch, and finally. Additionally, it includes examples demonstrating the use of try-catch blocks and common scenarios where exceptions may occur.

Uploaded by

st804055
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)
23 views90 pages

Java Exception Handling Explained

The document provides an overview of Exception Handling in Java, explaining its importance in maintaining the normal flow of applications during runtime errors. It details the types of exceptions, including checked and unchecked exceptions, and introduces the keywords used for handling exceptions such as try, catch, and finally. Additionally, it includes examples demonstrating the use of try-catch blocks and common scenarios where exceptions may occur.

Uploaded by

st804055
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

Unit_3

Exception Handling

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.

In this tutorial, we will learn about Java exceptions, it's types, and the difference between
checked and unchecked exceptions.

What is Exception in Java?


Dictionary Meaning: Exception is an abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.

Exception Handling is a mechanism to handle runtime errors such as


ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application; that
is why we need to handle exceptions. Let's consider a scenario:

1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;

Suppose there are 10 statements in a Java program and an exception occurs at


statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will not
be executed. However, when we perform exception handling, the rest of the
statements will be executed. That is why we use exception handling in Java.
Hierarchy of Java Exception classes
The [Link] class is the root class of Java Exception hierarchy inherited
by two subclasses: Exception and Error. The hierarchy of Java Exception classes is
given below:

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
Difference between Checked and Unchecked
Exceptions
1) Checked Exception

The classes that directly inherit the Throwable class except RuntimeException and
Error are known as checked exceptions. For example, IOException, SQLException, etc.
Checked exceptions are checked at compile-time.

2) Unchecked Exception

The classes that inherit the RuntimeException are known as unchecked exceptions.
For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable. Some examples of errors are OutOfMemoryError,


VirtualMachineError, AssertionError etc.
Java Exception Keywords
Java provides five keywords that are used to handle the exception. The following
table describes each.

Keyword Description

try The "try" keyword is used to specify a block where we should place an exception code.
It means we can't use try block alone. The try block must be followed by either catch or
finally.

catch The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block later.

finally The "finally" block is used to execute the necessary code of the program. It is executed
whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It specifies that there may occur
an exception in the method. It doesn't throw an exception. It is always used with
method signature.

Java Exception Handling Example


Let's see an example of Java Exception Handling in which we are using a try-catch
statement to handle the exception.

[Link]

1. public class JavaExceptionExample{


2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e){[Link](e);}
7. //rest code of the program
8. [Link]("rest of the code...");
9. }
10. }

Output:

Exception in thread main [Link]:/ by zero


rest of the code...

In the above example, 100/0 raises an ArithmeticException which is handled by a try-


catch block.

Common Scenarios of Java Exceptions


There are given some scenarios where unchecked exceptions may occur. They are as
follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on the variable
throws a NullPointerException.

1. String s=null;
2. [Link]([Link]());//NullPointerException

3) A scenario where NumberFormatException occurs

If the formatting of any variable or number is mismatched, it may result into


NumberFormatException. Suppose we have a string variable that has characters;
converting this variable into digit will cause NumberFormatException.

1. String s="abc";
2. int i=[Link](s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs

When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs.


there may be other reasons to occur ArrayIndexOutOfBoundsException. Consider the
following statements.

1. int a[]=new int[5];


2. a[10]=50; //ArrayIndexOutOfBoundsException

Java Exceptions Index


1. Java Try-Catch Block
2. Java Multiple Catch Block
3. Java Nested Try
4. Java Finally Block
5. Java Throw Keyword
6. Java Exception Propagation
7. Java Throws Keyword
8. Java Throw vs Throws
9. Java Final vs Finally vs Finalize
10. Java Exception Handling with Method Overriding
11. Java Custom Exceptions

Java try block


Java try block is used to enclose the code that might throw an exception. It must be
used within the method.

If an exception occurs at the particular statement in the try block, the rest of the
block code will not execute. So, it is recommended not to keep the code in try block
that will not throw an exception.

Java try block must be followed by either catch or finally block.

Syntax of Java try-catch


1. try{
2. //code that may throw an exception
3. }catch(Exception_class_Name ref){}

Syntax of try-finally block


1. try{
2. //code that may throw an exception
3. }finally{}

Java catch block


Java catch block is used to handle the Exception by declaring the type of exception
within the parameter. The declared exception must be the parent class exception (
i.e., Exception) or the generated exception type. However, the good approach is to
declare the generated type of exception.

The catch block must be used after the try block only. You can use multiple catch
block with a single try block.

Internal Working of Java try-catch block

The JVM firstly checks whether the exception is handled or not. If exception is not
handled, JVM provides a default exception handler that performs the following tasks:

o Prints out exception description.


o Prints the stack trace (Hierarchy of methods where the exception occurred).
o Causes the program to terminate.

But if the application programmer handles the exception, the normal flow of the
application is maintained, i.e., rest of the code is executed.

Problem without exception handling


Let's try to understand the problem if we don't use a try-catch block.

Example 1
[Link]

1. public class TryCatchExample1 {


2.
3. public static void main(String[] args) {
4.
5. int data=50/0; //may throw exception
6.
7. [Link]("rest of the code");
8.
9. }
10.
11. }

Output:

Exception in thread "main" [Link]: / by zero

As displayed in the above example, the rest of the code is not executed (in such
case, the rest of the code statement is not printed).

There might be 100 lines of code after the exception. If the exception is not handled,
all the code below the exception won't be executed.

Solution by exception handling


Let's see the solution of the above problem by a java try-catch block.
Example 2
[Link]

1. public class TryCatchExample2 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. //handling the exception
9. catch(ArithmeticException e)
10. {
11. [Link](e);
12. }
13. [Link]("rest of the code");
14. }
15.
16. }

Output:

[Link]: / by zero
rest of the code

As displayed in the above example, the rest of the code is executed, i.e., the rest of
the code statement is printed.

Example 3
In this example, we also kept the code in a try block that will not throw an exception.

[Link]

1. public class TryCatchExample3 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. // if exception occurs, the remaining statement will not exceute
8. [Link]("rest of the code");
9. }
10. // handling the exception
11. catch(ArithmeticException e)
12. {
13. [Link](e);
14. }
15.
16. }
17.
18. }

Output:

[Link]: / by zero

Here, we can see that if an exception occurs in the try block, the rest of the block
code will not execute.

Example 4
Here, we handle the exception using the parent class exception.

[Link]

1. public class TryCatchExample4 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. // handling the exception by using Exception class
9. catch(Exception e)
10. {
11. [Link](e);
12. }
13. [Link]("rest of the code");
14. }
15.
16. }

Output:

[Link]: / by zero
rest of the code

Example 5
Let's see an example to print a custom message on exception.

[Link]

1. public class TryCatchExample5 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. // handling the exception
9. catch(Exception e)
10. {
11. // displaying the custom message
12. [Link]("Can't divided by zero");
13. }
14. }
15.
16. }

Output:

Can't divided by zero

Example 6
Let's see an example to resolve the exception in a catch block.
[Link]

1. public class TryCatchExample6 {


2.
3. public static void main(String[] args) {
4. int i=50;
5. int j=0;
6. int data;
7. try
8. {
9. data=i/j; //may throw exception
10. }
11. // handling the exception
12. catch(Exception e)
13. {
14. // resolving the exception in catch block
15. [Link](i/(j+2));
16. }
17. }
18. }

Output:

25

Example 7
In this example, along with try block, we also enclose exception code in a catch block.

[Link]

1. public class TryCatchExample7 {


2.
3. public static void main(String[] args) {
4.
5. try
6. {
7. int data1=50/0; //may throw exception
8.
9. }
10. // handling the exception
11. catch(Exception e)
12. {
13. // generating the exception in catch block
14. int data2=50/0; //may throw exception
15.
16. }
17. [Link]("rest of the code");
18. }
19. }

Output:

Exception in thread "main" [Link]: / by zero

Here, we can see that the catch block didn't contain the exception code. So, enclose
exception code within a try block and use catch block only to handle the exceptions.

Example 8
In this example, we handle the generated exception (Arithmetic Exception) with a
different type of exception class (ArrayIndexOutOfBoundsException).

[Link]

1. public class TryCatchExample8 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7.
8. }
9. // try to handle the ArithmeticException using ArrayIndexOutOfBoundsException
10. catch(ArrayIndexOutOfBoundsException e)
11. {
12. [Link](e);
13. }
14. [Link]("rest of the code");
15. }
16.
17. }

Output:

Exception in thread "main" [Link]: / by zero

Example 9
Let's see an example to handle another unchecked exception.

[Link]

1. public class TryCatchExample9 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int arr[]= {1,3,5,7};
7. [Link](arr[10]); //may throw exception
8. }
9. // handling the array exception
10. catch(ArrayIndexOutOfBoundsException e)
11. {
12. [Link](e);
13. }
14. [Link]("rest of the code");
15. }
16.
17. }

Output:

[Link]: 10
rest of the code

Example 10
Let's see an example to handle checked exception.
[Link]

1. import [Link];
2. import [Link];
3.
4. public class TryCatchExample10 {
5.
6. public static void main(String[] args) {
7.
8.
9. PrintWriter pw;
10. try {
11. pw = new PrintWriter("[Link]"); //may throw exception
12. [Link]("saved");
13. }
14. // providing the checked exception handler
15. catch (FileNotFoundException e) {
16.
17. [Link](e);
18. }
19. [Link]("File saved successfully");
20. }
21. }

Output:

File saved successfully

Java Multi-catch block


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.

Points to remember
o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.

Flowchart of Multi-catch Block

Example 1
Let's see a simple example of java multi-catch block.

[Link]

1. public class MultipleCatchBlock1 {


2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7. a[5]=30/0;
8. }
9. catch(ArithmeticException e)
10. {
11. [Link]("Arithmetic Exception occurs");
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. [Link]("ArrayIndexOutOfBounds Exception occurs");
16. }
17. catch(Exception e)
18. {
19. [Link]("Parent Exception occurs");
20. }
21. [Link]("rest of the code");
22. }
23. }

Output:

Arithmetic Exception occurs


rest of the code

Example 2
[Link]

1. public class MultipleCatchBlock2 {


2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7.
8. [Link](a[10]);
9. }
10. catch(ArithmeticException e)
11. {
12. [Link]("Arithmetic Exception occurs");
13. }
14. catch(ArrayIndexOutOfBoundsException e)
15. {
16. [Link]("ArrayIndexOutOfBounds Exception occurs");
17. }
18. catch(Exception e)
19. {
20. [Link]("Parent Exception occurs");
21. }
22. [Link]("rest of the code");
23. }
24. }

Output:

ArrayIndexOutOfBounds Exception occurs


rest of the code

In this example, try block contains two exceptions. But at a time only one exception
occurs and its corresponding catch block is executed.

[Link]

1. public class MultipleCatchBlock3 {


2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7. a[5]=30/0;
8. [Link](a[10]);
9. }
10. catch(ArithmeticException e)
11. {
12. [Link]("Arithmetic Exception occurs");
13. }
14. catch(ArrayIndexOutOfBoundsException e)
15. {
16. [Link]("ArrayIndexOutOfBounds Exception occurs");
17. }
18. catch(Exception e)
19. {
20. [Link]("Parent Exception occurs");
21. }
22. [Link]("rest of the code");
23. }
24. }

Output:

Arithmetic Exception occurs


rest of the code

Example 4
In this example, we generate NullPointerException, but didn't provide the
corresponding exception type. In such case, the catch block containing the parent
exception class Exception will invoked.

[Link]

1. public class MultipleCatchBlock4 {


2.
3. public static void main(String[] args) {
4.
5. try{
6. String s=null;
7. [Link]([Link]());
8. }
9. catch(ArithmeticException e)
10. {
11. [Link]("Arithmetic Exception occurs");
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. [Link]("ArrayIndexOutOfBounds Exception occurs");
16. }
17. catch(Exception e)
18. {
19. [Link]("Parent Exception occurs");
20. }
21. [Link]("rest of the code");
22. }
23. }

Output:

Parent Exception occurs


rest of the code

Example 5
Let's see an example, to handle the exception without maintaining the order of
exceptions (i.e. from most specific to most general).

[Link]

1. class MultipleCatchBlock5{
2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(Exception e){[Link]("common task completed");}
8. catch(ArithmeticException e){[Link]("task1 is completed");}
9. catch(ArrayIndexOutOfBoundsException e){[Link]("task 2 completed");}
10. [Link]("rest of the code...");
11. }
12. }

Output:

Compile-time error
Java Nested try block
In Java, using a try block inside another try block is permitted. It is called as nested
try block. Every statement that we enter a statement in try block, context of that
exception is pushed onto the stack.

For example, the inner try block can be used to


handle ArrayIndexOutOfBoundsException while the outer try block can handle
the ArithemeticException (division by zero).

Why use nested try block


Sometimes a situation may arise where a part of a block may cause one error and the
entire block itself may cause another error. In such cases, exception handlers have to
be nested.

Syntax:
1. ....
2. //main try block
3. try
4. {
5. statement 1;
6. statement 2;
7. //try catch block within another try block
8. try
9. {
10. statement 3;
11. statement 4;
12. //try catch block within nested try block
13. try
14. {
15. statement 5;
16. statement 6;
17. }
18. catch(Exception e2)
19. {
20. //exception message
21. }
22.
23. }
24. catch(Exception e1)
25. {
26. //exception message
27. }
28. }
29. //catch block of parent (outer) try block
30. catch(Exception e3)
31. {
32. //exception message
33. }
34. ....

Java Nested try Example


Example 1
Let's see an example where we place a try block within another try block for two
different exceptions.

[Link]

1. public class NestedTryBlock{


2. public static void main(String args[]){
3. //outer try block
4. try{
5. //inner try block 1
6. try{
7. [Link]("going to divide by 0");
8. int b =39/0;
9. }
10. //catch block of inner try block 1
11. catch(ArithmeticException e)
12. {
13. [Link](e);
14. }
15.
16.
17. //inner try block 2
18. try{
19. int a[]=new int[5];
20.
21. //assigning the value out of array bounds
22. a[5]=4;
23. }
24.
25. //catch block of inner try block 2
26. catch(ArrayIndexOutOfBoundsException e)
27. {
28. [Link](e);
29. }
30.
31.
32. [Link]("other statement");
33. }
34. //catch block of outer try block
35. catch(Exception e)
36. {
37. [Link]("handled the exception (outer catch)");
38. }
39.
40. [Link]("normal flow..");
41. }
42. }

Output:
When any try block does not have a catch block for a particular exception, then the
catch block of the outer (parent) try block are checked for that exception, and if it
matches, the catch block of outer try block is executed.

If none of the catch block specified in the code is unable to handle the exception,
then the Java runtime system will handle the exception. Then it displays the system
generated message for that exception.

Example 2
Let's consider the following example. Here the try block within nested try block (inner
try block 2) do not handle the exception. The control is then transferred to its parent
try block (inner try block 1). If it does not handle the exception, then the control is
transferred to the main try block (outer try block) where the appropriate catch block
handles the exception. It is termed as nesting.

[Link]

1. public class NestedTryBlock2 {


2.
3. public static void main(String args[])
4. {
5. // outer (main) try block
6. try {
7.
8. //inner try block 1
9. try {
10.
11. // inner try block 2
12. try {
13. int arr[] = { 1, 2, 3, 4 };
14.
15. //printing the array element out of its bounds
16. [Link](arr[10]);
17. }
18.
19. // to handles ArithmeticException
20. catch (ArithmeticException e) {
21. [Link]("Arithmetic exception");
22. [Link](" inner try block 2");
23. }
24. }
25.
26. // to handle ArithmeticException
27. catch (ArithmeticException e) {
28. [Link]("Arithmetic exception");
29. [Link]("inner try block 1");
30. }
31. }
32.
33. // to handle ArrayIndexOutOfBoundsException
34. catch (ArrayIndexOutOfBoundsException e4) {
35. [Link](e4);
36. [Link](" outer (main) try block");
37. }
38. catch (Exception e5) {
39. [Link]("Exception");
40. [Link](" handled in main try-block");
41. }
42. }
43. }

Output:
Java finally block
Java finally block is a block used to execute important code such as closing the
connection, etc.

Java finally block is always executed whether an exception is handled or not.


Therefore, it contains all the necessary statements that need to be printed regardless
of the exception occurs or not.

The finally block follows the try-catch block.

Flowchart of finally block

Note: If you don't handle the exception, before terminating the program, JVM executes
finally block (if any).

Why use Java finally block?


o finally block in Java can be used to put "cleanup" code such as closing a file, closing
connection, etc.
o The important statements to be printed can be placed in the finally block.
Usage of Java finally
Let's see the different cases where Java finally block can be used.

Case 1: When an exception does not occur


Let's see the below example where the Java program does not throw any exception,
and the finally block is executed after the try block.

[Link]

1. class TestFinallyBlock {
2. public static void main(String args[]){
3. try{
4. //below code do not throw any exception
5. int data=25/5;
6. [Link](data);
7. }
8. //catch won't be executed
9. catch(NullPointerException e){
10. [Link](e);
11. }
12. //executed regardless of exception occurred or not
13. finally {
14. [Link]("finally block is always executed");
15. }
16.
17. [Link]("rest of phe code...");
18. }
19. }

Output:
Case 2: When an exception occurr but not handled by the catch
block
Let's see the the fillowing example. Here, the code throws an exception however the
catch block cannot handle it. Despite this, the finally block is executed after the try
block and then the program terminates abnormally.

[Link]

1. public class TestFinallyBlock1{


2. public static void main(String args[]){
3.
4. try {
5.
6. [Link]("Inside the try block");
7.
8. //below code throws divide by zero exception
9. int data=25/0;
10. [Link](data);
11. }
12. //cannot handle Arithmetic type exception
13. //can only accept Null Pointer type exception
14. catch(NullPointerException e){
15. [Link](e);
16. }
17.
18. //executes regardless of exception occured or not
19. finally {
20. [Link]("finally block is always executed");
21. }
22.
23. [Link]("rest of the code...");
24. }
25. }

Output:
Case 3: When an exception occurs and is handled by the catch
block
Example:

Let's see the following example where the Java code throws an exception and the
catch block handles the exception. Later the finally block is executed after the try-
catch block. Further, the rest of the code is also executed normally.

[Link]

1. public class TestFinallyBlock2{


2. public static void main(String args[]){
3.
4. try {
5.
6. [Link]("Inside try block");
7.
8. //below code throws divide by zero exception
9. int data=25/0;
10. [Link](data);
11. }
12.
13. //handles the Arithmetic Exception / Divide by zero exception
14. catch(ArithmeticException e){
15. [Link]("Exception handled");
16. [Link](e);
17. }
18.
19. //executes regardless of exception occured or not
20. finally {
21. [Link]("finally block is always executed");
22. }
23.
24. [Link]("rest of the code...");
25. }
26. }

Output:

Rule: For each try block there can be zero or more catch blocks, but only one finally
block.

Note: The finally block will not be executed if the program exits (either by calling
[Link]() or by causing a fatal error that causes the process to abort).

Java throw Exception


In Java, exceptions allows us to write good quality codes where the errors are
checked at the compile time instead of runtime and we can create custom exceptions
making the code recovery and debugging easier.

Java throw keyword


The Java throw keyword is used to throw an exception explicitly.

We specify the exception object which is to be thrown. The Exception has some
message with it that provides the error description. These exceptions may be related
to user inputs, server, etc.

We can throw either checked or unchecked exceptions in Java by throw keyword. It is


mainly used to throw a custom exception. We will discuss custom exceptions later in
this section.

We can also define our own set of conditions and throw an exception explicitly using
throw keyword. For example, we can throw ArithmeticException if we divide a
number by another number. Here, we just need to set the condition and throw
exception using throw keyword.
The syntax of the Java throw keyword is given below.

throw Instance i.e.,

1. throw new exception_class("error message");

Let's see the example of throw IOException.

1. throw new IOException("sorry device error");

Where the Instance must be of type Throwable or subclass of Throwable. For


example, Exception is the sub class of Throwable and the user-defined exceptions
usually extend the Exception class.

Java throw keyword Example


Example 1: Throwing Unchecked Exception
In this example, we have created a method named validate() that accepts an integer
as a parameter. If the age is less than 18, we are throwing the ArithmeticException
otherwise print a message welcome to vote.

[Link]

In this example, we have created the validate method that takes integer value as a
parameter. If the age is less than 18, we are throwing the ArithmeticException
otherwise print a message welcome to vote.

1. public class TestThrow1 {


2. //function to check if person is eligible to vote or not
3. public static void validate(int age) {
4. if(age<18) {
5. //throw Arithmetic exception if not eligible to vote
6. throw new ArithmeticException("Person is not eligible to vote");
7. }
8. else {
9. [Link]("Person is eligible to vote!!");
10. }
11. }
12. //main method
13. public static void main(String args[]){
14. //calling the function
15. validate(13);
16. [Link]("rest of the code...");
17. }
18. }

Output:

The above code throw an unchecked exception. Similarly, we can also throw
unchecked and user defined exceptions.

Note: If we throw unchecked exception from a method, it is must to handle the exception
or declare in throws clause.

If we throw a checked exception using throw keyword, it is must to handle the


exception using catch block or the method must declare it using throws declaration.

Example 2: Throwing Checked Exception


Note: Every subclass of Error and RuntimeException is an unchecked exception in Java.
A checked exception is everything else under the Throwable class.

[Link]

1. import [Link].*;
2.
3. public class TestThrow2 {
4.
5. //function to check if person is eligible to vote or not
6. public static void method() throws FileNotFoundException {
7.
8. FileReader file = new FileReader("C:\\Users\\Anurati\\Desktop\\[Link]");
9. BufferedReader fileInput = new BufferedReader(file);
10.
11.
12. throw new FileNotFoundException();
13.
14. }
15. //main method
16. public static void main(String args[]){
17. try
18. {
19. method();
20. }
21. catch (FileNotFoundException e)
22. {
23. [Link]();
24. }
25. [Link]("rest of the code...");
26. }
27. }

Output:

Example 3: Throwing User-defined Exception


Exception is everything else under the Throwable class.

[Link]

1. // class represents user-defined exception


2. class UserDefinedException extends Exception
3. {
4. public UserDefinedException(String str)
5. {
6. // Calling constructor of parent Exception
7. super(str);
8. }
9. }
10. // Class that uses above MyException
11. public class TestThrow3
12. {
13. public static void main(String args[])
14. {
15. try
16. {
17. // throw an object of user defined exception
18. throw new UserDefinedException("This is user-defined exception");
19. }
20. catch (UserDefinedException ude)
21. {
22. [Link]("Caught the exception");
23. // Print the message from MyException object
24. [Link]([Link]());
25. }
26. }
27. }

Output:

Java Exception Propagation


An exception is first thrown from the top of the stack and if it is not caught, it drops
down the call stack to the previous method. If not caught there, the exception again
drops down to the previous method, and so on until they are caught or until they
reach the very bottom of the call stack. This is called exception propagation.

Note: By default Unchecked Exceptions are forwarded in calling chain (propagated).

Exception Propagation Example


[Link]

1. class TestExceptionPropagation1{
2. void m(){
3. int data=50/0;
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){[Link]("exception handled");}
12. }
13. public static void main(String args[]){
14. TestExceptionPropagation1 obj=new TestExceptionPropagation1();
15. obj.p();
16. [Link]("normal flow...");
17. }
18. }

Output:

exception handled
normal flow...

In the above example exception occurs in the m() method where it is not handled, so
it is propagated to the previous n() method where it is not handled, again it is
propagated to the p() method where exception is handled.

Exception can be handled in any method in call stack either in the main() method, p()
method, n() method or m() method.
Note: By default, Checked Exceptions are not forwarded in calling chain (propagated).

Exception Propagation Example


[Link]

1. class TestExceptionPropagation2{
2. void m(){
3. throw new [Link]("device error");//checked exception
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){[Link]("exception handeled");}
12. }
13. public static void main(String args[]){
14. TestExceptionPropagation2 obj=new TestExceptionPropagation2();
15. obj.p();
16. [Link]("normal flow");
17. }
18. }
Output:

Compile Time Error

Java throws keyword


The Java throws keyword is used to declare an exception. It gives an information to
the programmer that there may occur an exception. So, it is better for the
programmer to provide the exception handling code so that the normal flow of the
program can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there occurs
any unchecked exception such as NullPointerException, it is programmers' fault that
he is not checking the code before it being used.

Syntax of Java throws


1. return_type method_name() throws exception_class_name{
2. //method code
3. }

Which exception should be declared?


Ans: Checked exception only, because:

o unchecked exception: under our control so we can correct our code.


o error: beyond our control. For example, we are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.

Advantage of Java throws keyword


Now Checked Exception can be propagated (forwarded in call stack).

It provides information to the caller of the method about the exception.

Java throws Example


Let's see the example of Java throws clause which describes that checked exceptions
can be propagated by throws keyword.

[Link]

1. import [Link];
2. class Testthrows1{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exception
5. }
6. void n()throws IOException{
7. m();
8. }
9. void p(){
10. try{
11. n();
12. }catch(Exception e){[Link]("exception handled");}
13. }
14. public static void main(String args[]){
15. Testthrows1 obj=new Testthrows1();
16. obj.p();
17. [Link]("normal flow...");
18. }
19. }

Output:

exception handled
normal flow...

Rule: If we are calling a method that declares an exception, we must either caught or
declare the exception.

There are two cases:

1. Case 1: We have caught the exception i.e. we have handled the exception using
try/catch block.
2. Case 2: We have declared the exception i.e. specified throws keyword with the
method.

Case 1: Handle Exception Using try-catch block


In case we handle the exception, the code will be executed fine whether exception
occurs during the program or not.

[Link]
1. import [Link].*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. public class Testthrows2{
8. public static void main(String args[]){
9. try{
10. M m=new M();
11. [Link]();
12. }catch(Exception e){[Link]("exception handled");}
13.
14. [Link]("normal flow...");
15. }
16. }

Output:

exception handled
normal flow...

Case 2: Declare Exception


o In case we declare the exception, if exception does not occur, the code will be
executed fine.
o In case we declare the exception and the exception occurs, it will be thrown at
runtime because throws does not handle the exception.

Let's see examples for both the scenario.

A) If exception does not occur

[Link]

1. import [Link].*;
2. class M{
3. void method()throws IOException{
4. [Link]("device operation performed");
5. }
6. }
7. class Testthrows3{
8. public static void main(String args[])throws IOException{//declare exception
9. M m=new M();
10. [Link]();
11.
12. [Link]("normal flow...");
13. }
14. }

Output:

device operation performed


normal flow...

B) If exception occurs

[Link]

1. import [Link].*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. class Testthrows4{
8. public static void main(String args[])throws IOException{//declare exception
9. M m=new M();
10. [Link]();
11.
12. [Link]("normal flow...");
13. }
14. }

Output:
Difference between throw and throws in Java
The throw and throws is the concept of exception handling where the throw keyword
throw the exception explicitly from a method or a block of code whereas the throws
keyword is used in signature of the method.

There are many differences between throw and throws keywords. A list of differences
between throw and throws are given below:

Sr. Basis of Differences throw throws


no.

1. Definition Java throw keyword is used Java throws keyword is used


throw an exception in the method signature to
explicitly in the code, inside declare an exception which
the function or the block of might be thrown by the
code. function while the execution
of the code.

2. Type of exception Using throw Using throws keyword, we


keyword, we can only can declare both checked
propagate unchecked and unchecked exceptions.
exception i.e., the checked However, the throws
exception cannot be keyword can be used to
propagated using throw only. propagate checked
exceptions only.

3. Syntax The throw keyword is The throws keyword is


followed by an instance of followed by class names of
Exception to be thrown. Exceptions to be thrown.

4. Declaration throw is used within the throws is used with the


method. method signature.

5. Internal implementation We are allowed to throw We can declare multiple


only one exception at a exceptions using throws
time i.e. we cannot throw keyword that can be thrown
multiple exceptions. by the method. For example,
main() throws IOException,
SQLException.

Java throw Example


[Link]

1. public class TestThrow {


2. //defining a method
3. public static void checkNum(int num) {
4. if (num < 1) {
5. throw new ArithmeticException("\nNumber is negative, cannot calculate square");
6. }
7. else {
8. [Link]("Square of " + num + " is " + (num*num));
9. }
10. }
11. //main method
12. public static void main(String[] args) {
13. TestThrow obj = new TestThrow();
14. [Link](-3);
15. [Link]("Rest of the code..");
16. }
17. }

Output:

Java throws Example


[Link]
1. public class TestThrows {
2. //defining a method
3. public static int divideNum(int m, int n) throws ArithmeticException {
4. int div = m / n;
5. return div;
6. }
7. //main method
8. public static void main(String[] args) {
9. TestThrows obj = new TestThrows();
10. try {
11. [Link]([Link](45, 0));
12. }
13. catch (ArithmeticException e){
14. [Link]("\nNumber cannot be divided by 0");
15. }
16.
17. [Link]("Rest of the code..");
18. }
19. }

Output:

Java throw and throws Example


[Link]

1. public class TestThrowAndThrows


2. {
3. // defining a user-defined method
4. // which throws ArithmeticException
5. static void method() throws ArithmeticException
6. {
7. [Link]("Inside the method()");
8. throw new ArithmeticException("throwing ArithmeticException");
9. }
10. //main method
11. public static void main(String args[])
12. {
13. try
14. {
15. method();
16. }
17. catch(ArithmeticException e)
18. {
19. [Link]("caught in main() method");
20. }
21. }
22. }

Output:

Difference between final, finally and finalize


The final, finally, and finalize are keywords in Java that are used in exception
handling. Each of these keywords has a different functionality. The basic difference
between final, finally and finalize is that the final is an access modifier, finally is the
block in Exception Handling and finalize is the method of object class.

Along with this, there are many differences between final, finally and finalize. A list of
differences between final, finally and finalize are given below:

Sr. Key final finally finalize


no.
1. Definition final is the keyword finally is the block in finalize is the method in
and access modifier Java Exception Handling Java which is used to
which is used to apply to execute the important perform clean up
restrictions on a class, code whether the processing just before
method or variable. exception occurs or not. object is garbage
collected.

2. Applicable Final keyword is used Finally block is always finalize() method is used
to with the classes, related to the try and with the objects.
methods and catch block in exception
variables. handling.

3. Functionality (1) Once declared, (1) finally block runs the finalize method
final variable becomes important code even if performs the cleaning
constant and cannot exception occurs or not. activities with respect to
be modified. (2) finally block cleans the object before its
(2) final method up all the resources destruction.
cannot be overridden used in try block
by sub class.
(3) final class cannot
be inherited.

4. Execution Final method is Finally block is executed finalize method is


executed only when as soon as the try-catch executed just before the
we call it. block is executed. object is destroyed.

It's execution is not


dependant on the
exception.

Java final Example


Let's consider the following example where we declare final variable age. Once
declared it cannot be modified.

[Link]

1. public class FinalExampleTest {


2. //declaring final variable
3. final int age = 18;
4. void display() {
5.
6. // reassigning value to age variable
7. // gives compile time error
8. age = 55;
9. }
10.
11. public static void main(String[] args) {
12.
13. FinalExampleTest obj = new FinalExampleTest();
14. // gives compile time error
15. [Link]();
16. }
17. }

Output:

In the above example, we have declared a variable final. Similarly, we can declare the
methods and classes final using the final keyword.

Java finally Example


Let's see the below example where the Java code throws an exception and the catch
block handles that exception. Later the finally block is executed after the try-catch
block. Further, the rest of the code is also executed normally.

[Link]

1. public class FinallyExample {


2. public static void main(String args[]){
3. try {
4. [Link]("Inside try block");
5. // below code throws divide by zero exception
6. int data=25/0;
7. [Link](data);
8. }
9. // handles the Arithmetic Exception / Divide by zero exception
10. catch (ArithmeticException e){
11. [Link]("Exception handled");
12. [Link](e);
13. }
14. // executes regardless of exception occurred or not
15. finally {
16. [Link]("finally block is always executed");
17. }
18. [Link]("rest of the code...");
19. }
20. }

Output:

Java finalize Example


[Link]

1. public class FinalizeExample {


2. public static void main(String[] args)
3. {
4. FinalizeExample obj = new FinalizeExample();
5. // printing the hashcode
6. [Link]("Hashcode is: " + [Link]());
7. obj = null;
8. // calling the garbage collector using gc()
9. [Link]();
10. [Link]("End of the garbage collection");
11. }
12. // defining the finalize method
13. protected void finalize()
14. {
15. [Link]("Called the finalize() method");
16. }
17. }

Output:

Exception Handling with Method Overriding in


Java
There are many rules if we talk about method overriding with exception handling.

Some of the rules are listed below:

o If the superclass method does not declare an exception


o If the superclass method does not declare an exception, subclass overridden
method cannot declare the checked exception but it can declare unchecked
exception.
o If the superclass method declares an exception
o If the superclass method declares an exception, subclass overridden method
can declare same, subclass exception or no exception but cannot declare
parent exception.

If the superclass method does not declare an exception


Rule 1: If the superclass method does not declare an exception, subclass overridden
method cannot declare the checked exception.

Let's consider following example based on the above rule.


[Link]

1. import [Link].*;
2. class Parent{
3.
4. // defining the method
5. void msg() {
6. [Link]("parent method");
7. }
8. }
9.
10. public class TestExceptionChild extends Parent{
11.
12. // overriding the method in child class
13. // gives compile time error
14. void msg() throws IOException {
15. [Link]("TestExceptionChild");
16. }
17.
18. public static void main(String args[]) {
19. Parent p = new TestExceptionChild();
20. [Link]();
21. }
22. }

Output:

Rule 2: If the superclass method does not declare an exception, subclass overridden
method cannot declare the checked exception but can declare unchecked exception.

[Link]

1. import [Link].*;
2. class Parent{
3. void msg() {
4. [Link]("parent method");
5. }
6. }
7.
8. class TestExceptionChild1 extends Parent{
9. void msg()throws ArithmeticException {
10. [Link]("child method");
11. }
12.
13. public static void main(String args[]) {
14. Parent p = new TestExceptionChild1();
15. [Link]();
16. }
17. }

Output:

If the superclass method declares an exception


Rule 1: If the superclass method declares an exception, subclass overridden method
can declare the same subclass exception or no exception but cannot declare parent
exception.

Example in case subclass overridden method declares parent


exception
[Link]

1. import [Link].*;
2. class Parent{
3. void msg()throws ArithmeticException {
4. [Link]("parent method");
5. }
6. }
7.
8. public class TestExceptionChild2 extends Parent{
9. void msg()throws Exception {
10. [Link]("child method");
11. }
12.
13. public static void main(String args[]) {
14. Parent p = new TestExceptionChild2();
15.
16. try {
17. [Link]();
18. }
19. catch (Exception e){}
20.
21. }
22. }

Output:

Example in case subclass overridden method declares same


exception
[Link]

1. import [Link].*;
2. class Parent{
3. void msg() throws Exception {
4. [Link]("parent method");
5. }
6. }
7.
8. public class TestExceptionChild3 extends Parent {
9. void msg()throws Exception {
10. [Link]("child method");
11. }
12.
13. public static void main(String args[]){
14. Parent p = new TestExceptionChild3();
15.
16. try {
17. [Link]();
18. }
19. catch(Exception e) {}
20. }
21. }

Output:

Example in case subclass overridden method declares


subclass exception
[Link]

1. import [Link].*;
2. class Parent{
3. void msg()throws Exception {
4. [Link]("parent method");
5. }
6. }
7.
8. class TestExceptionChild4 extends Parent{
9. void msg()throws ArithmeticException {
10. [Link]("child method");
11. }
12.
13. public static void main(String args[]){
14. Parent p = new TestExceptionChild4();
15.
16. try {
17. [Link]();
18. }
19. catch(Exception e) {}
20. }
21. }

Output:

ADVERTISEMENT

Example in case subclass overridden method declares no


exception
[Link]

1. import [Link].*;
2. class Parent {
3. void msg()throws Exception{
4. [Link]("parent method");
5. }
6. }
7.
8. class TestExceptionChild5 extends Parent{
9. void msg() {
10. [Link]("child method");
11. }
12.
13. public static void main(String args[]){
14. Parent p = new TestExceptionChild5();
15.
16. try {
17. [Link]();
18. }
19. catch(Exception e) {}
20.
21. }
22. }

Output:

Multithreading in Java

Multithreading is a Java feature that allows concurrent execution of two or


more parts of a program for maximum utilization of CPU. Each part of such
program is called a thread. So, threads are light-weight processes within a
process.
Threads can be created by using two mechanisms :
1. Extending the Thread class
2. Implementing the Runnable Interface
Thread creation by extending the Thread class
We create a class that extends the [Link] class. This class
overrides the run() method available in the Thread class. A thread begins its
life inside run() method. We create an object of our new class and call start()
method to start the execution of a thread. Start() invokes the run() method on
the Thread object.
 Java

// Java code for thread creation by extending

// the Thread class

class MultithreadingDemo extends Thread {

public void run()


{

try {

// Displaying the thread that is running

[Link](

"Thread " + [Link]().getId()

+ " is running");

catch (Exception e) {

// Throwing an exception

[Link]("Exception is caught");

// Main Class

public class Multithread {

public static void main(String[] args)

int n = 8; // Number of threads

for (int i = 0; i < n; i++) {

MultithreadingDemo object

= new MultithreadingDemo();
[Link]();

Output
Thread 15 is running
Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running
Thread 18 is running
Thread 17 is running
Thread creation by implementing the Runnable Interface
We create a new class which implements [Link] interface and
override run() method. Then we instantiate a Thread object and call start()
method on this object.

// Java code for thread creation by implementing

// the Runnable Interface

class MultithreadingDemo implements Runnable {

public void run()

try {

// Displaying the thread that is running

[Link](
"Thread " + [Link]().getId()

+ " is running");

catch (Exception e) {

// Throwing an exception

[Link]("Exception is caught");

// Main Class

class Multithread {

public static void main(String[] args)

int n = 8; // Number of threads

for (int i = 0; i < n; i++) {

Thread object

= new Thread(new MultithreadingDemo());

[Link]();

}
Output
Thread 13 is running
Thread 11 is running
Thread 12 is running
Thread 15 is running
Thread 14 is running
Thread 18 is running
Thread 17 is running
Thread 16 is running
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.
3. Using runnable will give you an object that can be shared amongst
multiple threads.

Java Thread Model


The Java language and its run-time system was designed keeping in mind about
multithreading. The run-time system depend upon multithreading. Java provides
asynchronous thread environment, this helps to increase the utilization of CPU.
Multithreading is best in all cases in contrast with single-thread model. Single-thread
system uses an approach of event loop with polling. According to this approach a
single thread in the system runs in an infinite loop. Polling the mechanism, that
selects a single event from the event queue to choose what to do next. As the event
is selected, then event loop forwards the control to the corresponding required
event handler. Nothing else can be happened, until the event handler returns.
Because of this CPU time is wasted. Here, only one part of the complete program is
dominating the whole system, and preventing the system to execute or start any
other process. In single-thread model one thread blocks all other threads until its
execution completes. On other waiting or idle thread can start and acquire the
resource which is not in use by the current thread. This causes the wastage of
resources.

Java’s multithreading provides benefit in this area by eliminating the loop and
polling mechanism, one thread can be paused without stopping the other parts of
the program. If any thread is paused or blocked, still other threads continue to run.
As the process has several states, similarly a thread exists in several states. A
thread can be in the following states:
Ready to run (New): First time as soon as it gets CPU time.
Running: Under execution.
Suspended: Temporarily not active or under execution.
Blocked: Waiting for resources.
Resumed: Suspended thread resumed, and start from where it left off.
Terminated: Halts the execution immediately and never resumes.

Java thread model can be defined in the following three sections:


Thread Priorities

Each thread has its own priority in Java. Thread priority is an absolute integer value.
Thread priority decides only when a thread switches from one running thread to
next, called context switching. Priority does increase the running time of the thread
or gives faster execution.
Synchronization

Java supports an asynchronous multithreading, any number of thread can run


simultaneously without disturbing other to access individual resources at different
instant of time or shareable resources. But some time it may be possible that
shareable resources are used by at least two threads or more than two threads, one
has to write at the same time, or one has to write and other thread is in the middle
of reading it. For such type of situations and circumstances Java implements
synchronization model called monitor. The monitor was first defined by C.A.R.
Hoare. You can consider the monitor as a box, in which only one thread can reside.
As a thread enter in monitor, all other threads have to wait until that thread exits
from the monitor. In such a way, a monitor protects the shareable resources used
by it being manipulated by other waiting threads at the same instant of time. Java
provides a simple methodology to implement
synchronization.
Messaging

A program is a collection of more than one thread. Threads can communicate with
each other. Java supports messaging between the threads with lost-cost. It provides
methods to all objects for inter-thread communication. As a thread exits from
synchronization state, it notifies all the waiting threads.

Life cycle of a Thread (Thread States)


In Java, a thread always exists in any one of the following states. These states are:

1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated

Explanation of Different Thread States


New: Whenever a new thread is created, it is always in the new state. For a thread in
the new state, the code has not been run yet and thus has not begun its execution.

Active: When a thread invokes the start() method, it moves from the new state to the
active state. The active state contains two states within it: one is runnable, and the
other is running.

o Runnable: A thread, that is ready to run is then moved to the runnable state. In the
runnable state, the thread may be running or may be ready to run at any given
instant of time. It is the duty of the thread scheduler to provide the thread time to
run, i.e., moving the thread the running state.
A program implementing multithreading acquires a fixed slice of time to each
individual thread. Each and every thread runs for a short span of time and when that
allocated time slice is over, the thread voluntarily gives up the CPU to the other
thread, so that the other threads can also run for their slice of time. Whenever such a
scenario occurs, all those threads that are willing to run, waiting for their turn to run,
lie in the runnable state. In the runnable state, there is a queue where the threads lie.
o Running: When the thread gets the CPU, it moves from the runnable to the running
state. Generally, the most common change in the state of a thread is from runnable
to running and again back to runnable.
Blocked or Waiting: Whenever a thread is inactive for a span of time (not
permanently) then, either the thread is in the blocked state or is in the waiting state.

For example, a thread (let's say its name is A) may want to print some data from the
printer. However, at the same time, the other thread (let's say its name is B) is using
the printer to print some data. Therefore, thread A has to wait for thread B to use the
printer. Thus, thread A is in the blocked state. A thread in the blocked state is unable
to perform any execution and thus never consume any cycle of the Central
Processing Unit (CPU). Hence, we can say that thread A remains idle until the thread
scheduler reactivates thread A, which is in the waiting or blocked state.

When the main thread invokes the join() method then, it is said that the main thread
is in the waiting state. The main thread then waits for the child threads to complete
their tasks. When the child threads complete their job, a notification is sent to the
main thread, which again moves the thread from waiting to the active state.

If there are a lot of threads in the waiting or blocked state, then it is the duty of the
thread scheduler to determine which thread to choose and which one to reject, and
the chosen thread is then given the opportunity to run.

Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its
name is A) has entered the critical section of a code and is not willing to leave that
critical section. In such a scenario, another thread (its name is B) has to wait forever,
which leads to starvation. To avoid such scenario, a timed waiting state is given to
thread B. Thus, thread lies in the waiting state for a specific span of time, and not
forever. A real example of timed waiting is when we invoke the sleep() method on a
specific thread. The sleep() method puts the thread in the timed wait state. After the
time runs out, the thread wakes up and start its execution from when it has left
earlier.

Terminated: A thread reaches the termination state because of the following


reasons:

o When a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an unhandled
exception or segmentation fault.

A terminated thread means the thread is no more in the system. In other words, the
thread is dead, and there is no way one can respawn (active after kill) the dead
thread.

The following diagram shows the different states involved in the life cycle of a thread.
Implementation of Thread States
In Java, one can get the current state of a thread using
the [Link]() method. The [Link] class of Java provides
the constants ENUM to represent the state of a thread. These constants are:

1. public static final [Link] NEW

It represents the first state of a thread that is the NEW state.

1. public static final [Link] RUNNABLE

It represents the runnable [Link] means a thread is waiting in the queue to run.

1. public static final [Link] BLOCKED

It represents the blocked state. In this state, the thread is waiting to acquire a lock.

1. public static final [Link] WAITING

It represents the waiting state. A thread will go to this state when it invokes the
[Link]() method, or [Link]() method with no timeout. A thread in the
waiting state is waiting for another thread to complete its task.

1. public static final [Link] TIMED_WAITING

It represents the timed waiting state. The main difference between waiting and timed
waiting is the time constraint. Waiting has no time constraint, whereas timed waiting
has the time constraint. A thread invoking the following method reaches the timed
waiting state.
o sleep
o join with timeout
o wait with timeout
o parkUntil
o parkNanos

1. public static final [Link] TERMINATED

It represents the final state of a thread that is terminated or dead. A terminated


thread means it has completed its execution.

Java Program for Demonstrating Thread States


The following Java program shows some of the states of a thread defined above.

FileName: [Link]

1. // ABC class implements the interface Runnable


2. class ABC implements Runnable
3. {
4. public void run()
5. {
6.
7. // try-catch block
8. try
9. {
10. // moving thread t2 to the state timed waiting
11. [Link](100);
12. }
13. catch (InterruptedException ie)
14. {
15. [Link]();
16. }
17.
18.
19. [Link]("The state of thread t1 while it invoked the method join() on threa
d t2 -"+ [Link]());
20.
21. // try-catch block
22. try
23. {
24. [Link](200);
25. }
26. catch (InterruptedException ie)
27. {
28. [Link]();
29. }
30. }
31. }
32.
33. // ThreadState class implements the interface Runnable
34. public class ThreadState implements Runnable
35. {
36. public static Thread t1;
37. public static ThreadState obj;
38.
39. // main method
40. public static void main(String argvs[])
41. {
42. // creating an object of the class ThreadState
43. obj = new ThreadState();
44. t1 = new Thread(obj);
45.
46. // thread t1 is spawned
47. // The thread t1 is currently in the NEW state.
48. [Link]("The state of thread t1 after spawning it - " + [Link]());
49.
50. // invoking the start() method on
51. // the thread t1
52. [Link]();
53.
54. // thread t1 is moved to the Runnable state
55. [Link]("The state of thread t1 after invoking the method start() on it -
" + [Link]());
56. }
57.
58. public void run()
59. {
60. ABC myObj = new ABC();
61. Thread t2 = new Thread(myObj);
62.
63. // thread t2 is created and is currently in the NEW state.
64. [Link]("The state of thread t2 after spawning it - "+ [Link]());
65. [Link]();
66.
67. // thread t2 is moved to the runnable state
68. [Link]("the state of thread t2 after calling the method start() on it -
" + [Link]());
69.
70. // try-catch block for the smooth flow of the program
71. try
72. {
73. // moving the thread t1 to the state timed waiting
74. [Link](200);
75. }
76. catch (InterruptedException ie)
77. {
78. [Link]();
79. }
80.
81. [Link]("The state of thread t2 after invoking the method sleep() on it -
"+ [Link]() );
82.
83. // try-catch block for the smooth flow of the program
84. try
85. {
86. // waiting for thread t2 to complete its execution
87. [Link]();
88. }
89. catch (InterruptedException ie)
90. {
91. [Link]();
92. }
93. [Link]("The state of thread t2 when it has completed it's execution -
" + [Link]());
94. }
95.
96. }

Output:

The state of thread t1 after spawning it - NEW


The state of thread t1 after invoking the method start() on it - RUNNABLE
The state of thread t2 after spawning it - NEW
the state of thread t2 after calling the method start() on it - RUNNABLE
The state of thread t1 while it invoked the method join() on thread t2 -
TIMED_WAITING
The state of thread t2 after invoking the method sleep() on it -
TIMED_WAITING
The state of thread t2 when it has completed it's execution - TERMINATED

Explanation: Whenever we spawn a new thread, that thread attains the new state.
When the method start() is invoked on a thread, the thread scheduler moves that
thread to the runnable state. Whenever the join() method is invoked on any thread
instance, the current thread executing that statement has to wait for this thread to
finish its execution, i.e., move that thread to the terminated state. Therefore, before
the final print statement is printed on the console, the program invokes the method
join() on thread t2, making the thread t1 wait while the thread t2 finishes its
execution and thus, the thread t2 get to the terminated or dead state. Thread t1 goes
to the waiting state because it is waiting for thread t2 to finish it's execution as it has
invoked the method join() on thread t2.

There are two ways to create a thread:

1. By extending Thread class


2. By 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:


o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)

Commonly used methods of Thread class:


1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the [Link] calls the run() method on
the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public [Link] getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily
pause and allow other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method
named run().

1. public void run(): is used to perform action for a thread.

Starting a thread:
The start() method of Thread class is used to start a newly created thread. It
performs the following tasks:

o A new thread starts(with new callstack).


o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.

1) Java Thread Example by extending Thread class


FileName: [Link]

1. class Multi extends Thread{


2. public void run(){
3. [Link]("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. [Link]();
8. }
9. }

Output:

thread is running...

2) Java Thread Example by implementing Runnable interface


FileName: [Link]

1. class Multi3 implements Runnable{


2. public void run(){
3. [Link]("thread is running...");
4. }
5.
6. public static void main(String args[]){
7. Multi3 m1=new Multi3();
8. Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
9. [Link]();
10. }
11. }

Output:

thread is running...

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.

3) 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]

1. public class MyThread1


2. {
3. // Main method
4. public static void main(String argvs[])
5. {
6. // creating an object of the Thread class using the constructor Thread(String name)
7. Thread t= new Thread("My first thread");
8.
9. // the start() method moves the thread to the active state
10. [Link]();
11. // getting the thread name by invoking the getName() method
12. String str = [Link]();
13. [Link](str);
14. }
15. }
Output:

My first thread

4) Using the Thread Class: Thread(Runnable r, String name)


Observe the following program.

FileName: [Link]

1. public class MyThread2 implements Runnable


2. {
3. public void run()
4. {
5. [Link]("Now the thread is running ...");
6. }
7.
8. // main method
9. public static void main(String argvs[])
10. {
11. // creating an object of the class MyThread2
12. Runnable r1 = new MyThread2();
13.
14. // creating an object of the class Thread using Thread(Runnable r, String name)
15. Thread th1 = new Thread(r1, "My new thread");
16.
17. // the start() method moves the thread to the active state
18. [Link]();
19.
20. // getting the thread name by invoking the getName() method
21. String str = [Link]();
22. [Link](str);
23. }
24. }

Output:

My new thread
Now the thread is running ...
Thread Scheduler in Java
A component of Java that decides which thread to run or execute and which thread
to wait is called a thread scheduler in Java. In Java, a thread is only chosen by a
thread scheduler if it is in the runnable state. However, if there is more than one
thread in the runnable state, it is up to the thread scheduler to pick one of the
threads and ignore the other ones. There are some criteria that decide which thread
will execute first. There are two factors for scheduling a thread i.e. Priority and Time
of arrival.

Priority: Priority of each thread lies between 1 to 10. If a thread has a higher priority,
it means that thread has got a better chance of getting picked up by the thread
scheduler.

Time of Arrival: Suppose two threads of the same priority enter the runnable state,
then priority cannot be the factor to pick a thread from these two threads. In such a
case, arrival time of thread is considered by the thread scheduler. A thread that
arrived first gets the preference over the other threads.

Thread Scheduler Algorithms


On the basis of the above-mentioned factors, the scheduling algorithm is followed
by a Java thread scheduler.

First Come First Serve Scheduling:


In this scheduling algorithm, the scheduler picks the threads thar arrive first in the
runnable queue. Observe the following table:

Threads Time of Arrival

t1 0

t2 1

t3 2

t4 3
In the above table, we can see that Thread t1 has arrived first, then Thread t2, then
t3, and at last t4, and the order in which the threads will be processed is according to
the time of arrival of threads.

Hence, Thread t1 will be processed first, and Thread t4 will be processed last.

Time-slicing scheduling:
Usually, the First Come First Serve algorithm is non-preemptive, which is bad as it
may lead to infinite blocking (also known as starvation). To avoid that, some time-
slices are provided to the threads so that after some time, the running thread has to
give up the CPU. Thus, the other waiting threads also get time to run their job.

In the above diagram, each thread is given a time slice of 2 seconds. Thus, after 2
seconds, the first thread leaves the CPU, and the CPU is then captured by Thread2.
The same process repeats for the other threads too.
Preemptive-Priority Scheduling:
The name of the scheduling algorithm denotes that the algorithm is related to the
priority of the threads.

Suppose there are multiple threads available in the runnable state. The thread
scheduler picks that thread that has the highest priority. Since the algorithm is also
preemptive, therefore, time slices are also provided to the threads to avoid
starvation. Thus, after some time, even if the highest priority thread has not
completed its job, it has to release the CPU because of preemption.

Working of the Java Thread Scheduler


Let's understand the working of the Java thread scheduler. Suppose, there are five
threads that have different arrival times and different priorities. Now, it is the
responsibility of the thread scheduler to decide which thread will get the CPU first.

The thread scheduler selects the thread that has the highest priority, and the thread
begins the execution of the job. If a thread is already in runnable state and another
thread (that has higher priority) reaches in the runnable state, then the current thread
is pre-empted from the processor, and the arrived thread with higher priority gets
the CPU time.

When two threads (Thread 2 and Thread 3) having the same priorities and arrival
time, the scheduling will be decided on the basis of FCFS algorithm. Thus, the thread
that arrives first gets the opportunity to execute first.

[Link]() in Java with Examples


The Java Thread class provides the two variant of the sleep() method. First one
accepts only an arguments, whereas the other variant accepts two arguments. The
method sleep() is being used to halt the working of a thread for a given amount of
time. The time up to which the thread remains in the sleeping state is known as the
sleeping time of the thread. After the sleeping time is over, the thread starts its
execution from where it has left.
The sleep() Method Syntax:
Following are the syntax of the sleep() method.

1. public static void sleep(long mls) throws InterruptedException


2. public static void sleep(long mls, int n) throws InterruptedException

The method sleep() with the one parameter is the native method, and the
implementation of the native method is accomplished in another programming
language. The other methods having the two parameters are not the native method.
That is, its implementation is accomplished in Java. We can access the sleep()
methods with the help of the Thread class, as the signature of the sleep() methods
contain the static keyword. The native, as well as the non-native method, throw a
checked Exception. Therefore, either try-catch block or the throws keyword can work
here.

The [Link]() method can be used with any thread. It means any other thread or
the main thread can invoke the sleep() method.

Parameters:
The following are the parameters used in the sleep() method.

mls: The time in milliseconds is represented by the parameter mls. The duration for
which the thread will sleep is given by the method sleep().

n: It shows the additional time up to which the programmer or developer wants the
thread to be in the sleeping state. The range of n is from 0 to 999999.

The method does not return anything.

Important Points to Remember About the Sleep() Method


Whenever the [Link]() methods execute, it always halts the execution of the
current thread.

Whenever another thread does interruption while the current thread is already in the
sleep mode, then the InterruptedException is thrown.

If the system that is executing the threads is busy, then the actual sleeping time of
the thread is generally more as compared to the time passed in arguments. However,
if the system executing the sleep() method has less load, then the actual sleeping
time of the thread is almost equal to the time passed in the argument.
Example of the sleep() method in Java : on the custom thread
The following example shows how one can use the sleep() method on the custom
thread.

FileName: [Link]

1. class TestSleepMethod1 extends Thread{


2. public void run(){
3. for(int i=1;i<5;i++){
4. // the thread will sleep for the 500 milli seconds
5. try{[Link](500);}catch(InterruptedException e){[Link](e);}
6. [Link](i);
7. }
8. }
9. public static void main(String args[]){
10. TestSleepMethod1 t1=new TestSleepMethod1();
11. TestSleepMethod1 t2=new TestSleepMethod1();
12.
13. [Link]();
14. [Link]();
15. }
16. }

Output:

1
1
2
2
3
3
4
4

As you know well that at a time only one thread is executed. If you sleep a thread for
the specified time, the thread scheduler picks up another thread and so on.

Example of the sleep() Method in Java : on the main thread


FileName: [Link]
1. // important import statements
2. import [Link];
3. import [Link].*;
4.
5.
6. public class TestSleepMethod2
7. {
8. // main method
9. public static void main(String argvs[])
10. {
11.
12. try {
13. for (int j = 0; j < 5; j++)
14. {
15.
16. // The main thread sleeps for the 1000 milliseconds, which is 1 sec
17. // whenever the loop runs
18. [Link](1000);
19.
20. // displaying the value of the variable
21. [Link](j);
22. }
23. }
24. catch (Exception expn)
25. {
26. // catching the exception
27. [Link](expn);
28. }
29. }
30. }

Output:

0
1
2
3
4
Example of the sleep() Method in Java: When the sleeping time
is -ive
The following example throws the exception IllegalArguementException when the
time for sleeping is negative.

FileName: [Link]

1. // important import statements


2. import [Link];
3. import [Link].*;
4.
5. public class TestSleepMethod3
6. {
7. // main method
8. public static void main(String argvs[])
9. {
10. // we can also use throws keyword followed by
11. // exception name for throwing the exception
12. try
13. {
14. for (int j = 0; j < 5; j++)
15. {
16.
17. // it throws the exception IllegalArgumentException
18. // as the time is -ive which is -100
19. [Link](-100);
20.
21. // displaying the variable's value
22. [Link](j);
23. }
24. }
25. catch (Exception expn)
26. {
27.
28. // the exception iscaught here
29. [Link](expn);
30. }
31. }
32. }

Output:

[Link]: timeout value is negative

Can we start a thread twice


No. After starting a thread, it can never be started again. If you does so,
an IllegalThreadStateException is thrown. In such case, thread will run once but for
second time, it will throw exception.

Let's understand it by the example given below:

1. public class TestThreadTwice1 extends Thread{


2. public void run(){
3. [Link]("running...");
4. }
5. public static void main(String args[]){
6. TestThreadTwice1 t1=new TestThreadTwice1();
7. [Link]();
8. [Link]();
9. }
10. }

Output:

running
Exception in thread "main" [Link]

Runnable interface in Java

[Link] is an interface that is to be implemented by a class


whose instances are intended to be executed by a thread. There are two
ways to start a new Thread – Subclass Thread and implement Runnable.
There is no need of subclassing a Thread when a task can be done by
overriding only run() method of Runnable.
Steps to create a new thread using Runnable
1. Create a Runnable implementer and implement the run() method.
2. Instantiate the Thread class and pass the implementer to the Thread,
Thread has a constructor which accepts Runnable instances.
3. Invoke start() of Thread instance, start internally calls run() of the
implementer. Invoking start() creates a new Thread that executes the
code written in run(). Calling run() directly doesn’t create and start a new
Thread, it will run in the same thread. To start a new line of execution, call
start() on the thread.
Example 1
 java

public class RunnableDemo {

public static void main(String[] args)

[Link]("Main thread is- "

+ [Link]().getName());

Thread t1 = new Thread(new RunnableDemo().new


RunnableImpl());

[Link]();

private class RunnableImpl implements Runnable {

public void run()

{
[Link]([Link]().getName()

+ ", executing run() method!");

Output:
Main thread is- main
Thread-0, executing run() method!
The output shows two active threads in the program – main thread and
Thread-0, main method is executed by the Main thread but invoking the start
on RunnableImpl creates and starts a new thread – Thread-0. What
happens when Runnable encounters an exception ? Runnable can’t
throw checked exception but RuntimeException can be thrown from the
run(). Uncaught exceptions are handled by the exception handler of the
thread, if JVM can’t handle or catch exceptions, it prints the stack trace and
terminates the flow.

Inter-thread Communication in Java

Inter-thread communication or Co-operation is all about allowing synchronized


threads to communicate with each other.

Cooperation (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 [Link] is implemented by following methods
of Object class:

o wait()
o notify()
o notifyAll()
1) wait() method
The wait() method causes current thread to release the lock and wait until either
another thread invokes the notify() method or the notifyAll() method for this object,
or a specified amount of time has elapsed.

The current thread must own this object's monitor, so it must be called from the
synchronized method only otherwise it will throw exception.

Method Description

public final void wait()throws InterruptedException It waits until object is notified.

public final void wait(long timeout)throws It waits for the specified amount of
InterruptedException time.

2) notify() method
The notify() method wakes up a single thread that is waiting on this object's monitor.
If any threads are waiting on this object, one of them is chosen to be awakened. The
choice is arbitrary and occurs at the discretion of the implementation.

Syntax:

1. public final void notify()

3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.

Syntax:

1. public final void notifyAll()

Understanding the process of inter-thread


communication
The point to point explanation of the above diagram is as follows:

1. Threads enter to acquire lock.


2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it
releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable
state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of
the object.

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.

Difference between wait and sleep?


Let's see the important differences between wait and sleep methods.

wait() sleep()

The wait() method releases the lock. The sleep() method doesn't release the lock.
It is a method of Object class It is a method of Thread class

It is the non-static method It is the static method

It should be notified by notify() or notifyAll() After the specified amount of time, sleep is
methods completed.

Example of Inter Thread Communication in Java


Let's see the simple example of inter thread communication.

[Link]

1. class Customer{
2. int amount=10000;
3.
4. synchronized void withdraw(int amount){
5. [Link]("going to withdraw...");
6.
7. if([Link]<amount){
8. [Link]("Less balance; waiting for deposit...");
9. try{wait();}catch(Exception e){}
10. }
11. [Link]-=amount;
12. [Link]("withdraw completed...");
13. }
14.
15. synchronized void deposit(int amount){
16. [Link]("going to deposit...");
17. [Link]+=amount;
18. [Link]("deposit completed... ");
19. notify();
20. }
21. }
22.
23. class Test{
24. public static void main(String args[]){
25. final Customer c=new Customer();
26. new Thread(){
27. public void run(){[Link](15000);}
28. }.start();
29. new Thread(){
30. public void run(){[Link](10000);}
31. }.start();
32.
33. }}

Output:

going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed

Java Thread suspend() method

The suspend() method of thread class puts the thread from running to waiting state.
This method is used if you want to stop the thread execution and start it again when
a certain event occurs. This method allows a thread to temporarily cease execution.
The suspended thread can be resumed using the resume() method.

Syntax
1. public final void suspend()

Return
This method does not return any value.

Exception
SecurityException: If the current thread cannot modify the thread.

Example
1. public class JavaSuspendExp extends Thread
2. {
3. public void run()
4. {
5. for(int i=1; i<5; i++)
6. {
7. try
8. {
9. // thread to sleep for 500 milliseconds
10. sleep(500);
11. [Link]([Link]().getName());
12. }catch(InterruptedException e){[Link](e);}
13. [Link](i);
14. }
15. }
16. public static void main(String args[])
17. {
18. // creating three threads
19. JavaSuspendExp t1=new JavaSuspendExp ();
20. JavaSuspendExp t2=new JavaSuspendExp ();
21. JavaSuspendExp t3=new JavaSuspendExp ();
22. // call run() method
23. [Link]();
24. [Link]();
25. // suspend t2 thread
26. [Link]();
27. // call run() method
28. [Link]();
29. }
30. }

Output:

Thread-0
1
Thread-2
1
Thread-0
2
Thread-2
2
Thread-0
3
Thread-2
3
Thread-0
4
Thread-2
4

Java Thread resume() method


The resume() method of thread class is only used with suspend() method. This
method is used to resume a thread which was suspended using suspend() method.
This method allows the suspended thread to start again.

Syntax
1. public final void resume()

Return value
This method does not return any value.

Exception
SecurityException: If the current thread cannot modify the thread.

Example
1. public class JavaResumeExp extends Thread
2. {
3. public void run()
4. {
5. for(int i=1; i<5; i++)
6. {
7. try
8. {
9. // thread to sleep for 500 milliseconds
10. sleep(500);
11. [Link]([Link]().getName());
12. }catch(InterruptedException e){[Link](e);}
13. [Link](i);
14. }
15. }
16. public static void main(String args[])
17. {
18. // creating three threads
19. JavaResumeExp t1=new JavaResumeExp ();
20. JavaResumeExp t2=new JavaResumeExp ();
21. JavaResumeExp t3=new JavaResumeExp ();
22. // call run() method
23. [Link]();
24. [Link]();
25. [Link](); // suspend t2 thread
26. // call run() method
27. [Link]();
28. [Link](); // resume t2 thread
29. }
30. }

Output:

Thread-0
1
Thread-2
1
Thread-1
1
Thread-0
2
Thread-2
2
Thread-1
2
Thread-0
3
Thread-2
3
Thread-1
3
Thread-0
4
Thread-2
4
Thread-1
4
The stop() method of thread class terminates the thread execution. Once a thread is
stopped, it cannot be restarted by start() method.

Syntax
1. public final void stop()
2. public final void stop(Throwable obj)

Parameter
obj : The Throwable object to be thrown.

Return
This method does not return any value.

Exception
SecurityException: This exception throws if the current thread cannot modify the
thread.

Example
1. public class JavaStopExp extends Thread
2. {
3. public void run()
4. {
5. for(int i=1; i<5; i++)
6. {
7. try
8. {
9. // thread to sleep for 500 milliseconds
10. sleep(500);
11. [Link]([Link]().getName());
12. }catch(InterruptedException e){[Link](e);}
13. [Link](i);
14. }
15. }
16. public static void main(String args[])
17. {
18. // creating three threads
19. JavaStopExp t1=new JavaStopExp ();
20. JavaStopExp t2=new JavaStopExp ();
21. JavaStopExp t3=new JavaStopExp ();
22. // call run() method
23. [Link]();
24. [Link]();
25. // stop t3 thread
26. [Link]();
27. [Link]("Thread t3 is stopped");
28. }
29. }

You might also like