0% found this document useful (0 votes)
0 views15 pages

Java Programming Unit-III Part-I

The document provides an overview of exception handling and multithreading in Java, detailing the fundamentals of exception types, handling mechanisms, and the importance of maintaining normal application flow. It explains checked and unchecked exceptions, their causes, and includes examples of using try-catch blocks, multiple catch clauses, and nested try statements. Additionally, it discusses the termination and resumptive models of exception handling, along with the concept of uncaught exceptions.

Uploaded by

Vinay Vinnu
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)
0 views15 pages

Java Programming Unit-III Part-I

The document provides an overview of exception handling and multithreading in Java, detailing the fundamentals of exception types, handling mechanisms, and the importance of maintaining normal application flow. It explains checked and unchecked exceptions, their causes, and includes examples of using try-catch blocks, multiple catch clauses, and nested try statements. Additionally, it discusses the termination and resumptive models of exception handling, along with the concept of uncaught exceptions.

Uploaded by

Vinay Vinnu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND SCIENCE

KARMNAGAR
(Approved by AICTE, New Delhi and- Affiliated
505481 to JNTU, Hyderabad)

II B.Tech II- Semester Java Programming (R18) 2021-22

II B.Tech II- Semester


CS405PC
Java Programming (R18) 2021-22

UNIT-III PART-I

Prepared by N.Venkateswaran, Associate Professor, CSE Dept Page 1


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND SCIENCE
KARMNAGAR
(Approved by AICTE, New Delhi and- Affiliated
505481 to JNTU, Hyderabad)

II B.Tech II- Semester Java Programming (R18) 2021-22


UNIT-III

Exception handling - Fundamentals of exception handling, Exception types, Termination


or resumptive models, Uncaught exceptions, using try and catch, multiple catch clauses,
nested try statements, throw, throws and finally, built- in exceptions, creating own exception
sub classes.
Multithreading- Differences between thread-based multitasking and process-based
multitasking, Java thread model, creating threads, thread priorities, synchronizing threads,
inter thread communication.

Exception Handling in Java

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.

An exception in java programming is an abnormal situation that is raised during the program
execution. In simple words, an exception is a problem that arises at the time of program
execution.

When an exception occurs, it disrupts the program execution flow. When an exception
occurs, the program execution gets terminated, and the system generates an error. We use
the exception handling mechanism to avoid abnormal termination of program execution.

Java programming language has a very powerful and efficient exception handling
mechanism with a large number of built-in classes to handle most of the exceptions
automatically.

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.
Prepared by N.Venkateswaran, Associate Professor, CSE Dept Page 2
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND SCIENCE
KARMNAGAR
(Approved by AICTE, New Delhi and- Affiliated
505481 to JNTU, Hyderabad)

II B.Tech II- Semester Java Programming (R18) 2021-22


However, when we perform exception handling, the rest of the statements will be executed.
That is why we use exception handling in Java.

Java programming language has the following class hierarchy to support the exception
handling mechanism.

Reasons for Exception Occurrence


Several reasons lead to the occurrence of an exception. A few of them are as follows.
 When we try to open a file that does not exist may lead to an exception.
 When the user enters invalid input data, it may lead to an exception.
 When a network connection has lost during the program execution may lead to an
exception.
 When we try to access the memory beyond the allocated range may lead to an
exception.
 The physical device problems may also lead to an exception.

Prepared by N.Venkateswaran, Associate Professor, CSE Dept Page 3


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND SCIENCE
KARMNAGAR
(Approved by AICTE, New Delhi and- Affiliated
505481 to JNTU, Hyderabad)

II B.Tech II- Semester Java Programming (R18) 2021-22


Types of Exception
In java, exceptions have categorized into two types, and they are as follows.
 Checked Exception - An exception that is checked by the compiler at the time of
compilation is called a checked exception.

 Unchecked Exception - An exception that cannot be caught by the compiler but


occurs at the time of program execution is called an unchecked exception.

How exceptions handled in Java?


In java, the exception handling mechanism uses five keywords
namely try, catch, finally, throw, and throws.

Checked Exceptions
The checked exception is an exception that is checked by the compiler during the
compilation process to confirm whether the exception is handled by the programmer or not.
If it is not handled, the compiler displays a compilation error using built-in classes. The
checked exception is also known as a compile-time exception.

The checked exceptions are generally caused by faults outside of the code itself like missing
resources, networking errors, and problems with threads come to mind.

The following are a few built-in classes used to handle checked exceptions in java.

 IOException
 FileNotFoundException
 ClassNotFoundException
 SQLException
 DataAccessException
 InstantiationException
 UnknownHostException
Note:
In the exception class hierarchy, the checked exception classes are the direct children of the
Exception class.

Example:
import java.io.*;

public class CheckedExceptions {

public static void main(String[] args) {

File f_ref = new File("C:\\User\\Desktop\\varun\\Sample.txt");


try {
FileReader fr = new FileReader(f_ref);
}catch(Exception e) {

Prepared by N.Venkateswaran, Associate Professor, CSE Dept Page 4


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND SCIENCE
KARMNAGAR
(Approved by AICTE, New Delhi and- Affiliated
505481 to JNTU, Hyderabad)

II B.Tech II- Semester Java Programming (R18) 2021-22


System.out.println(e);
}
}
}
Output:
java.io.FileNotFoundException: C:\User\Desktop\varun\Sample.txt (The system cannot find
the path specified)

Unchecked Exceptions
The unchecked exception is an exception that occurs at the time of program execution. The
unchecked exceptions are not caught by the compiler at the time of compilation. The
unchecked exception is also known as a runtime exception.

The unchecked exceptions are generally caused due to bugs such as logic errors, improper
use of resources, etc.

The following are a few built-in classes used to handle unchecked exceptions in java.

Built-in Exceptions Description


It is thrown when an exceptional condition has
ArithmeticException
occurred in an arithmetic operation.
It is thrown to indicate that an array has been
accessed with an illegal index. The index is
ArrayIndexOutOfBoundsException
either negative or greater than or equal to the size
of the array.
This exception is raised when we try to access a
ClassNotFoundException
class whose definition is not found.
An exception that is raised when a file is not
FileNotFoundException
accessible or does not open.
It is thrown when an input-output operation is
IOException
failed or interrupted.
It is thrown when a thread is waiting, sleeping, or
InterruptedException
doing some processing, and it is interrupted.
It is thrown when a class does not contain the
NoSuchFieldException
field (or variable) specified.
Note:
In the exception class hierarchy, the unchecked exception classes are the children of
Runtime Exception class, which is a child class of Exception class.

Example:
public class UncheckedException {

public static void main(String[] args) {

int list[] = {10, 20, 30, 40, 50};

System.out.println(list[6]); //ArrayIndexOutOfBoundsException
Prepared by N.Venkateswaran, Associate Professor, CSE Dept Page 5
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND SCIENCE
KARMNAGAR
(Approved by AICTE, New Delhi and- Affiliated
505481 to JNTU, Hyderabad)

II B.Tech II- Semester Java Programming (R18) 2021-22

String msg=null;
System.out.println(msg.length()); //NullPointerException

String name="abc";
int i=Integer.parseInt(name); //NumberFormatException
}
}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at UncheckedException.main(UncheckedException.java:7)

Exception Models in Java


Java programming language has two models of exception handling. The exception models
that java supports are as follows.

 Termination Model
 Resumptive Model

Termination Model
In the termination model, when a method encounters an exception, further processing in that
method is terminated and control is transferred to the nearest catch block that can handle the
type of exception encountered.

Resumptive Model
The alternative of termination model is resumptive model. In resumptive model, the
exception handler is expected to do something to stable the situation, and then the faulting
method is retried. In resumptive model we hope to continue the execution after the
exception is handled.

Uncaught Exceptions in Java


In java, assume that, if we do not handle the exceptions in a program. In this case, when an
exception occurs in a particular function, then Java prints a exception message with the help
of uncaught exception handler.

The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.

Java programming language has a very strong exception handling mechanism. It allows us
to handle the exception use the keywords like try, catch, finally, throw and throws.

When an uncaught exception occurs, the JVM calls a special private method known
dispatchUncaughtException( ), on the Thread class in which the exception occurs and
terminates the thread.

The Division by zero exception is one of the example for uncaught exceptions.
Prepared by N.Venkateswaran, Associate Professor, CSE Dept Page 6
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND SCIENCE
KARMNAGAR
(Approved by AICTE, New Delhi and- Affiliated
505481 to JNTU, Hyderabad)

II B.Tech II- Semester Java Programming (R18) 2021-22


Example:
import java.util.Scanner;

public class UncaughtExceptionExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);


System.out.println("Enter the a and b values: ");
int a = read.nextInt();
int b = read.nextInt();
int c = a / b;
System.out.println(a + "/" + b +" = " + c);
}
}
Output:
Enter the a and b values:
25
5
25/5 = 5

Enter the a and b values:


25
0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at UncaughtExceptionExample.main(UncaughtExceptionExample.java:11)

In the above example, we are not used try and catch blocks, but when the value of b is zero
the division by zero exception occurs and it caught by the default exception handler.

try and catch in Java

In java, the try and catch, both are the keywords used for exception handling.

The try block contains a set of statements where an exception can occur. It is always
followed by a catch block, which handles the exception that occurs in the associated try
block. A try block must be followed by catch blocks or finally block or both.

A catch block is where you handle the exceptions. This block must follow the try block and
a single try block can have several catch blocks associated with it. You can catch different
exceptions in different catch blocks. When an exception occurs in a try block, the
corresponding catch block that handles that particular exception executes.
The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.

Prepared by N.Venkateswaran, Associate Professor, CSE Dept Page 7


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND SCIENCE
KARMNAGAR
(Approved by AICTE, New Delhi and- Affiliated
505481 to JNTU, Hyderabad)

II B.Tech II- Semester Java Programming (R18) 2021-22

Both try and catch are used as a pair. Every try block must have one or more catch blocks.
We cannot use try without atleast one catch, and catch alone can be used (catch without try
is not allowed).
The following is the syntax of try and catch blocks.
Syntax
try{
...
code to be tested
...
}
catch(ExceptionType object){
...
code for handling the exception
...
}
Example:
import java.util.Scanner;

public class TryCatchExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);


System.out.println("Enter the a and b values: ");
try {
int a = read.nextInt();
int b = read.nextInt();
int c = a / b;
System.out.println(a + "/" + b +" = " + c);
}
catch(ArithmeticException ae) {
System.out.println("Problem info: Value of divisor can not be ZERO");
}
}
}
Output:
Enter the a and b values:
25
5
25/5 = 5

Enter the a and b values:

Prepared by N.Venkateswaran, Associate Professor, CSE Dept Page 8


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND SCIENCE
KARMNAGAR
(Approved by AICTE, New Delhi and- Affiliated
505481 to JNTU, Hyderabad)

II B.Tech II- Semester Java Programming (R18) 2021-22


25
0
Problem info: Value of divisor cannot be ZERO

In the above example code, when an exception occurs in the try block the execution control
transferred to the catch block and the catch block handles it.

Multiple catch clauses


In java programming language, a try block may has one or more number of catch blocks.
That means a single try statement can have multiple catch clauses.

When a try block has more than one catch block, each catch block must contain a different
exception type to be handled.

The multiple catch clauses are defined when the try block contains the code that may lead to
different type of exceptions.

The try block generates only one exception at a time, and at a time only one catch block is
executed.

When there are multiple catch blocks, the order of catch blocks must be from the most
specific exception handler to most general.

The catch block with Exception class handler must be defined at the last.

Example:
public class TryMCatchExample {

public static void main(String[] args) {

try {
int list[] = new int[5];
list[2] = 10;
list[4] = 2;
list[10] = list[2] / list[4];
}
catch(ArithmeticException ae) {
System.out.println("Problem info: Value of divisor can not be ZERO.");
}
catch(ArrayIndexOutOfBoundsException aie) {
System.out.println("Problem info: ArrayIndexOutOfBoundsException has
occured.");
}
catch(Exception e) {

Prepared by N.Venkateswaran, Associate Professor, CSE Dept Page 9


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND SCIENCE
KARMNAGAR
(Approved by AICTE, New Delhi and- Affiliated
505481 to JNTU, Hyderabad)

II B.Tech II- Semester Java Programming (R18) 2021-22


System.out.println("Problem info: Unknown exception has occured.");
}
}
}
Output:
Problem info: ArrayIndexOutOfBoundsException has occurred.

Nested try statements


The java allows to write a try statement inside another try statement. A try block within
another try block is known as nested try block.

When there are nested try blocks, each try block must have one or more separate catch
blocks.
Example:
public class TryCatchMNExample {
public static void main(String[] args) {

try {
int list[] = new int[5];
list[2] = 10;
list[4] = 2;
list[0] = list[2] / list[4];
try {
list[10] = 100;
}
catch(ArrayIndexOutOfBoundsException aie) {
System.out.println("Problem info: ArrayIndexOutOfBoundsException has
occured.");
}
}
catch(ArithmeticException ae) {
System.out.println("Problem info: Value of divisor cannot be ZERO.");
}
catch(Exception e) {
System.out.println("Problem info: Unknown exception has occured.");
}
}
}

Output:
Problem info: ArrayIndexOutOfBoundsException has occurred.

Prepared by N.Venkateswaran, Associate Professor, CSE Dept Page 10


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND SCIENCE
KARMNAGAR
(Approved by AICTE, New Delhi and- Affiliated
505481 to JNTU, Hyderabad)

II B.Tech II- Semester Java Programming (R18) 2021-22


In case of nested try blocks, if an exception occurred in the inner try block and it's catch
blocks are unable to handle it then it transfers the control to the outer try's catch block to
handle it.

throw, throws, and finally keywords in Java


In java, the keywords throw, throws, and finally are used in the exception handling concept.
Let's look at each of these keywords.

throw keyword in Java


The throw keyword is used to throw an exception instance explicitly from a try block to
corresponding catch block. That means it is used to transfer the control from try block to
corresponding catch block.

The throw keyword must be used inside the try block. When JVM encounters the throw
keyword, it stops the execution of try block and jump to the corresponding catch block.

 Using throw keyword only object of Throwable class or its sub classes can be
thrown.
 Using throw keyword only one exception can be thrown.
 The throw keyword must followed by a throwable instance.

The following is the general syntax for using throw keyword in a try block.

Syntax
throw instance;

Here the instance must be throwable instance and it can be created dynamically using new operator.

Example:
import java.util.Scanner;

public class SampleThrow {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);


int num1, num2, result;
System.out.print("Enter any two numbers: ");
num1 = input.nextInt();
num2 = input.nextInt();
try {
if(num2 == 0)
throw new ArithmeticException("Division by zero is not possible");
result = num1 / num2;
System.out.println(num1 + "/" + num2 + "=" + result);
}
catch(ArithmeticException ae) {
System.out.println("Problem info: " + ae.getMessage());

Prepared by N.Venkateswaran, Associate Professor, CSE Dept Page 11


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND SCIENCE
KARMNAGAR
(Approved by AICTE, New Delhi and- Affiliated
505481 to JNTU, Hyderabad)

II B.Tech II- Semester Java Programming (R18) 2021-22


}
System.out.println("End of the program");
}
}
Output:
Enter any two numbers: 25
5
25/5=5
End of the program

Enter any two numbers: 25


0
Problem info: Division by zero is not possible
End of the program

throws keyword in Java


The throws keyword specifies the exceptions that a method can throw to the default handler
and does not handle itself. That means when we need a method to throw an exception
automatically, we use throws keyword followed by method declaration

When a method throws an exception, we must put the calling statement of method in try-catch block.

Example:
import java.util.Scanner;

public class ThrowsExample {

int num1, num2, result;


Scanner input = new Scanner(System.in);

void division() throws ArithmeticException {


System.out.print("Enter any two numbers: ");
num1 = input.nextInt();
num2 = input.nextInt();
result = num1 / num2;
System.out.println(num1 + "/" + num2 + "=" + result);
}

public static void main(String[] args) {

try {
new ThrowsExample().division();
}
catch(ArithmeticException ae) {
System.out.println("Problem info: " + ae.getMessage());
}
System.out.println("End of the program");
}
}

Prepared by N.Venkateswaran, Associate Professor, CSE Dept Page 12


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND SCIENCE
KARMNAGAR
(Approved by AICTE, New Delhi and- Affiliated
505481 to JNTU, Hyderabad)

II B.Tech II- Semester Java Programming (R18) 2021-22


Output:
Enter any two numbers: 36
6
36/6=6
End of the program

Enter any two numbers: 36


0
Problem info: / by zero
End of the program

throw vs throws
throw throws
1. Used to explicitly throw an exception 1. Used to declare an exception
2. Checked exceptions cannot be propagated using
2. Checked exceptions can be propagated
throw only
3. Followed by an instance 3. Followed by a class
4. Used within a method 4. Used with a method signature
5. Cannot throw multiple exceptions 5. Can declare multiple exceptions

finally keyword in Java

A finally block contains all the crucial statements that must be executed whether an
exception occurs or not. The statements present in this block will always execute, regardless
an exception occurs in the try block or not such as closing a connection, stream etc.

The basic purpose of finally keyword is to cleanup resources allocated by try block, such as
closing file, closing database connection, etc.

 Only one finally block is allowed for each try block.


 Use of finally block is optional.
Example:
import java.util.Scanner;

public class FinallyExample {

public static void main(String[] args) {


int num1, num2, result;
Scanner input = new Scanner(System.in);
System.out.print("Enter any two numbers: ");
num1 = input.nextInt();
num2 = input.nextInt();
try {
if(num2 == 0)
throw new ArithmeticException("Division by zero");
result = num1 / num2;

Prepared by N.Venkateswaran, Associate Professor, CSE Dept Page 13


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND SCIENCE
KARMNAGAR
(Approved by AICTE, New Delhi and- Affiliated
505481 to JNTU, Hyderabad)

II B.Tech II- Semester Java Programming (R18) 2021-22


System.out.println(num1 + "/" + num2 + "=" + result);
}
catch(ArithmeticException ae) {
System.out.println("Problem info: " + ae.getMessage());
}
finally {
System.out.println("The finally block executes always");
}
System.out.println("End of the program");
}
}
Output:
Enter any two numbers:
45
5
45/5=9
The finally block executes always
End of the program

Enter any two numbers:


70
0
Problem info: Division by zero
The finally block executes always
End of the program

Creating Own Exceptions in Java


Java provides the user with the option to create their own exceptions. Such exceptions are
known as Custom Exceptions or User-Defined Exceptions.

The Java programming language allows us to create our own exception classes which are
basically subclasses built-in class Exception.

To create our own exception class simply creates a class as a subclass of built-in Exception
class.
We may create constructor in the user-defined exception class and pass a string to Exception
class constructor using super(). We can use getMessage() method to access the string.
The following Java code that illustrates the creation of user-defined exception.
Example:
import java.util.Scanner;

class NotEligibleException extends Exception{


NotEligibleException(String msg){

Prepared by N.Venkateswaran, Associate Professor, CSE Dept Page 14


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND SCIENCE
KARMNAGAR
(Approved by AICTE, New Delhi and- Affiliated
505481 to JNTU, Hyderabad)

II B.Tech II- Semester Java Programming (R18) 2021-22


super(msg);
}
}

class VoterList{
int age;
VoterList(int age){
this.age = age;
}

void checkEligibility() {
try {
if(age < 18) {
throw new NotEligibleException("Error: Not eligible for vote due to under age.");
}
System.out.println("Congrates! You are eligible for vote.");
}
catch(NotEligibleException nee) {
System.out.println(nee.getMessage());
}
}
public static void main(String args[]) {

Scanner input = new Scanner(System.in);


System.out.println("Enter your age in years: ");
int age = input.nextInt();
VoterList person = new VoterList(age);
person.checkEligibility();
}
}
Output:
Enter your age in years:
21
Congrates! You are eligible for vote.

Enter your age in years:


17
Error: Not eligible for vote due to under age.

Prepared by N.Venkateswaran, Associate Professor, CSE Dept Page 15

You might also like