0% found this document useful (0 votes)
1 views

Exception Handling(27!03!25)

The document discusses exception handling in Java, explaining what exceptions are, their types (checked and unchecked), and how they can disrupt program execution. It details the mechanisms for handling exceptions using keywords like try, catch, throw, throws, and finally, along with examples of each. Additionally, it covers the models of exception handling (termination and resumptive) and the importance of managing uncaught exceptions.

Uploaded by

sarithainti444
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Exception Handling(27!03!25)

The document discusses exception handling in Java, explaining what exceptions are, their types (checked and unchecked), and how they can disrupt program execution. It details the mechanisms for handling exceptions using keywords like try, catch, throw, throws, and finally, along with examples of each. Additionally, it covers the models of exception handling (termination and resumptive) and the importance of managing uncaught exceptions.

Uploaded by

sarithainti444
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Concepts of exception handling:

An exception in java programming is an abnormal situation that is araised 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.
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.
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 can not be caught by the compiler but
occurrs 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.
We will learn all these concepts in this series of tutorials.

Exception Types in Java


In java, exceptions are mainly categorized into two types, and they are as follows.
 Checked Exceptions
 Unchecked Exceptions
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 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
↓_ In the exception class hierarchy, the checked exception classes are the direct children of
the Exception class.
The checked exception is also known as a compile-time exception.
Let's look at the following example program for the checked exception method.
Example - Checked Exceptions

import java.io.*;

public class CheckedExceptions {

public static void main(String[] args) {

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


try {
FileReader fr = new FileReader(f_ref);
}catch(Exception e) {
System.out.println(e);
}

}
}

When we run the above program, it produces the following output.

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 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.
 ArithmeticException
 NullPointerException
 NumberFormatException
 ArrayIndexOutOfBoundsException
 StringIndexOutOfBoundsException
_↓ In the exception class hierarchy, the unchecked exception classes are the children of
RuntimeException class, which is a child class of Exception class.
The unchecked exception is also known as a runtime exception.
Let's look at the following example program for the unchecked exceptions.
Example - Unchecked Exceptions

public class UncheckedException {

public static void main(String[] args) {

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

System.out.println(list[6]);
//ArrayIndexOutOfBoundsException

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

String name="abc";
int i=Integer.parseInt(name); //NumberFormatException
}

When we run the above program, it produces the following output.

Exception Models in Java


In java, there are two exception models. Java programming language has two models of
exception handling. The exception models that java suports are as follows.
 Termination Model
 Resumptive Model
Let's look into details of each exception 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.
In other words we can say that in termination model the error is so critical there is no way to
get back to where the exception occurred.

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.
In resumptive model we may use a method call that want resumption like behavior. We may
also place the try block in a while loop that keeps re-entering the try block util the result is
satisfactory.

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 allow 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. Look at the
following code.
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);

}
}

When we execute the above code, it produce the following output for the value a = 10 and b
= 0.

In the above example code, 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 trytry and catch, both are the keywords used for exception handling.
The keyword try is used to define a block of code that will be tests the occurence of an
exception. The keyword catch is used to define a block of code that handles the exception
occured in the respective try block.
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.
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
...
}

Consider the following example code to illustrate try and catch blocks in Java.
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");
}
}
}

When we run the above code, it produce the following output.


In the above example code, when an exception occurs in the try block the execution control
transfered 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 multipe 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.
Let's look at the following example Java code to illustrate multiple catch clauses.
Example

public class TryCatchExample {

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) {
System.out.println("Problem info: Unknown exception has occured.");
}
}
}

When we run the above code, it produce the following output.

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 seperate catch
blocks.
Let's look at the following example Java code to illustrate nested try statements.
Example

public class TryCatchExample {

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 can not be ZERO.");
}
catch(Exception e) {
System.out.println("Problem info: Unknown exception has occured.");
}
}
}

When we run the above code, it produce the following output.

_ In case of nested try blocks, if an exception occured 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 an throwable instance.
The following is the general syntax for using throw keyword in a try block.
Syntax

throw instance;

Here the instace must be throwable instance and it can be created dynamically using new
operator.
Let's look at the following example Java code to illustrate throw keyword.
Example

import java.util.Scanner;

public class Sample {

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());
}
System.out.println("End of the program");
}
}

When we run the above code, it produce the following output.


throws keyword in Java
The throws keyword is used to handle checked exceptions. As we learned in the previous
article that exceptions are of two types: checked and unchecked. Checked exception (compile
time) needs to be handled else the program won’t compile. On the other hand unchecked
exception (Runtime) doesn’t get checked during compilation. Throws keyword is used for
handling checked exceptions. You can declare multiple exceptions using throws keyword.

The throws keyword vs try-catch in Java


You may be wondering why we need throws keyword when we can handle exceptions using
try-catch block in Java. Well, thats a valid question. We already know we can handle
exceptions using try-catch block.

The throws keyword does the same thing that try-catch does but there are some cases where
you would prefer throws over try-catch. For example: Lets say we have a method
myMethod() the statements inside this method can throw either ArithmeticException or
NullPointerException, in this case you can use try-catch as shown below:

public void myMethod()


{
try {
// Statements that might throw an exception
}
catch (ArithmeticException e) {
// Exception handling statements
}
catch (NullPointerException e) {
// Exception handling statements
}
}
But suppose you have several such methods that can cause exceptions, in that case it would
be tedious to write these try-catch for each method. The code will become unnecessary long
and will be less-readable.

One way to overcome this problem is by using throws like this: declare the exceptions in the
method signature using throws and handle the exceptions where you are calling this method
by using try-catch.

Another advantage of using this approach is that you will be forced to handle the exception
when you call this method, all the exceptions that are declared using throws, must be handled
where you are calling this method else you will get compilation error.

public void myMethod() throws ArithmeticException, NullPointerException


{
// Statements that might throw an exception
}

public static void main(String args[]) {


try {
myMethod();
}
catch (ArithmeticException e) {
// Exception handling statements
}
catch (NullPointerException e) {
// Exception handling statements
}
}

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.

Let's look at the following example Java code to illustrate throws keyword.
Example
public class ThrowsExample2
{
void division() throws ArithmeticException,ArrayIndexOutOfBoundsException
{
int list[]=new int[5];
list[2]=10;
list[4]=2;
list[0]=list[2]/list[4];
list[10]=100;
}
public static void main(String[] args)
{
try
{
new ThrowsExample2().division();
}
catch(ArithmeticException ae)
{
System.out.println("Problem info: divide by zero");
}
catch(ArrayIndexOutOfBoundsException aie)
{
System.out.println("Problem info: ArrayIndexOutOfBounds Exception");
}
}
}

Output:
Problem info: ArrayIndexOutOfBounds Exception
finally keyword in Java
The finally keyword used to define a block that must be executed irrespective of exception
occurence.
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.
Let's look at the following example Java code to illustrate throws keyword.
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;
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");
}

When we run the above code, it produce the following output.


Built-in Exceptions in Java

The Java programming language has several built-in exception class that support exception
handling. Every exception class is suitable to explain certain error situations at run time.All
the built-in exception classes in Java were defined a package java.lang.

List of checked exceptions in Java


The following table shows the list of several checked exceptions.
S.
No. Exception Class with Description

1 ClassNotFoundException
It is thrown when the Java Virtual Machine (JVM) tries to load a particular class and
the specified class cannot be found in the classpath.

2 CloneNotSupportedException
Used to indicate that the clone method in class Object has been called to clone an
object, but that the object's class does not implement the Cloneable interface.

3 IllegalAccessException
It is thrown when one attempts to access a method or member that visibility qualifiers
do not allow.

4 InstantiationException
It is thrown when an application tries to create an instance of a class using the
newInstance method in class Class , but the specified class object cannot be instantiated
because it is an interface or is an abstract class.

5 InterruptedException
It is thrown when a thread that is sleeping, waiting, or is occupied is interrupted.

6 NoSuchFieldException
It indicates that the class doesn't have a field of a specified name.
S.
No. Exception Class with Description

7 NoSuchMethodException
It is thrown when some JAR file has a different version at runtime that it had at
compile time, a NoSuchMethodException occurs during reflection when we try to
access a method that does not exist.

List of unchecked exceptions in Java


The following table shows the list of several unchecked exceptions.

S.
No. Exception Class with Description

1 ArithmeticException
It handles the arithmetic exceptions like dividion by zero

2 ArrayIndexOutOfBoundsException
It handles the situations like an array has been accessed with an illegal index. The
index is either negative or greater than or equal to the size of the array.

3 ArrayStoreException
It handles the situations like when an attempt has been made to store the wrong type of
object into an array of objects

4 AssertionError
It is used to indicate that an assertion has failed

5 ClassCastException
It handles the situation when we try to improperly cast a class from one type to another.

6 IllegalArgumentException
This exception is thrown in order to indicate that a method has been passed an illegal or
inappropriate argument.

7 IllegalMonitorStateException
This indicates that the calling thread has attempted to wait on an object's monitor, or
has attempted to notify other threads that wait on an object's monitor, without owning
the specified monitor.

8 IllegalStateException
It signals that a method has been invoked at an illegal or inappropriate time.

9 IllegalThreadStateException
It is thrown by the Java runtime environment, when the programmer is trying to modify
the state of the thread when it is illegal.

10 IndexOutOfBoundsException
It is thrown when attempting to access an invalid index within a collection, such as an
S.
No. Exception Class with Description

array , vector , string , and so forth.

11 NegativeArraySizeException
It is thrown if an applet tries to create an array with negative size.

12 NullPointerException
it is thrown when program attempts to use an object reference that has the null value.

13 NumberFormatException
It is thrown when we try to convert a string into a numeric value such as float or
integer, but the format of the input string is not appropriate or illegal.

14 SecurityException
It is thrown by the Java Card Virtual Machine to indicate a security violation.

15 StringIndexOutOfBounds
It is thrown by the methods of the String class, in order to indicate that an index is
either negative, or greater than the size of the string itself.

16 UnsupportedOperationException
It is thrown to indicate that the requested operation is not supported.

Creating Own Exceptions in Java


In Java, we can create our own exceptions that are derived classes of the Exception class.
Creating our own Exception is known as custom exception or user-defined exception.
Basically, Java custom exceptions are used to customize the exception according to user
need.
Consider the example 1 in which InvalidAgeException class extends the Exception class.
Using the custom exception, we can have your own exception and message. Here, we have
passed a string to the constructor of superclass i.e. Exception class that can be obtained using
getMessage() method on the object we have created.
In this section, we will learn how custom exceptions are implemented and used in Java
programs.

Why use custom exceptions?


Java exceptions cover almost all the general type of exceptions that may occur in the
programming. However, we sometimes need to create custom exceptions.
Following are few of the reasons to use custom exceptions:
o To catch and provide specific treatment to a subset of existing Java exceptions.
o Business logic exceptions: These are the exceptions related to business logic and
workflow. It is useful for the application users or the developers to understand the
exact problem.
In order to create custom exception, we need to extend Exception class that belongs to
java.lang package.
Consider the following example, where we create a custom exception named
WrongFileNameException:
1. public class WrongFileNameException extends Exception {
2. public WrongFileNameException(String errorMessage) {
3. super(errorMessage);
4. }
5. }
Note: We need to write the constructor that takes the String as the error message and it is
called parent class constructor.
Example 1:
Let's see a simple example of Java custom exception. In the following code, constructor of
InvalidAgeException takes a string as an argument. This string is passed to constructor of
parent class Exception using the super() method. Also the constructor of Exception class can
be called without using a parameter and calling super() method is not mandatory.
TestCustomException1.java
1. // class representing custom exception
2. class InvalidAgeException extends Exception
3. {
4. public InvalidAgeException (String str)
5. {
6. // calling the constructor of parent Exception
7. super(str);
8. }
9. }
10. // class that uses custom exception InvalidAgeException
11. public class TestCustomException1
12. {
13. // method to check the age
14. static void validate (int age) throws InvalidAgeException{
15. if(age < 18){
16. // throw an object of user defined exception
17. throw new InvalidAgeException("age is not valid to vote");
18. }
19. else {
20. System.out.println("welcome to vote");
21. }
22. }
23. // main method
24. public static void main(String args[])
25. {
26. try
27. {
28. // calling the method
29. validate(13);
30. }
31. catch (InvalidAgeException ex)
32. {
33. System.out.println("Caught the exception");
34. // printing the message from InvalidAgeException object
35. System.out.println("Exception occured: " + ex);
36. }
37. System.out.println("rest of the code...");
38. }
39. }
Output:

You might also like