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

6

The document provides a comprehensive overview of Exception Handling in Java, explaining its importance in maintaining program flow during runtime errors. It details the Exception Hierarchy, types of exceptions (built-in and user-defined), and the keywords used for exception handling, including try, catch, throw, throws, and finally. Additionally, it includes examples of common exceptions and how to create custom exceptions.

Uploaded by

gvnbca
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 views11 pages

6

The document provides a comprehensive overview of Exception Handling in Java, explaining its importance in maintaining program flow during runtime errors. It details the Exception Hierarchy, types of exceptions (built-in and user-defined), and the keywords used for exception handling, including try, catch, throw, throws, and finally. Additionally, it includes examples of common exceptions and how to create custom exceptions.

Uploaded by

gvnbca
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/ 11

Exception Handling in Java

Exception Handling is a way of handling errors that occur during runtime and compile time. It
maintains your program flow despite runtime errors in the code and, thus, prevents unanticipated
crashes. It facilitates troubleshooting by providing error details and cutting down on development
time.

Exception Hierarchy in Java

Exception and Error are subclasses of Throwable, the hierarchy's base class. Exception, for example,
is used for exceptional conditions that user programs should catch. Error, on the other hand, is used
by the Java run-time system (JVM) to indicate errors related to the run-time environment (JRE),
such as StackOverflowError.

The hierarchy is divided into two branches:

1. Errors: An error is a severe condition that can occur only at run time and is irrecoverable. It
prevents a program from executing and cannot be handled by the programmer. An error
belongs to the java.lang.error class.

2. Exceptions: A programmer can catch and handle exceptions in his program code. When an
exception occurs within a method, an object called the exception object is created. This
object contains information about the exception, such as its name and description and the
state of the program when the exception occurred.

There are mainly two types of exceptions: user-defined and built-in.

1. Built-in Exceptions

These exceptions are present in Java libraries.

There are two types of built-in exceptions in Java:

 Checked Exception
Checked exceptions are classes that inherit directly from the Throwable class, with the exception
of RuntimeException and Error. Examples include IOException, SQLException, and so on. Checked
exceptions are checked at compilation time. They must be either caught by the code or declared in
the method signature using the throws keyword.

 Unchecked Exception

Classes that inherit the RuntimeException class are known as unchecked exceptions. Examples
include ArithmeticException, NullPointerException, and ArrayIndexOutOfBoundsException.
Unchecked exceptions are not checked at compile-time but rather at runtime by JVM. They do not
need to be explicitly caught or declared.

2. User-Defined Exceptions

User-defined exceptions are also known as custom exceptions derived from the Exception class
from java.lang package(Java package). The user creates these exceptions according to different
situations. Such exceptions are handled using five keywords: try, catch, throw, throws, and finally.

keywords in the Exception Handling Keywords in Java sectionbelow.

Errors Vs. Exceptions in Java

Errors Exceptions

Belongs to the java.lang.Error class defined in java.lang.Exception package

Errors are of Unchecked type Exceptions can be both checked and unchecked.

Errors mainly occur during run-


Only the unchecked exceptions are encountered in run-time.
time.

Exceptions can be handled using exception-handling


Errors are irrecoverable
mechanisms
Java Exception Handling Keywords

Java consists of five keywords to handle various kinds of custom exceptions. They are:

Keywor
Description
d
try The "try" keyword specifies an exception block.
specifies the code block to be executed if an exception occurs in
catch
the try block.
the finally block will always be executed whether an exception
finally
occurs or not
throw the "throw" keyword triggers an exception
throws The "throws" keyword declares an exception.
1. try

 A try block consists of all the doubtful statements that can throw exceptions.

 A try block cannot be executed on itself; it requires at least one catch block or finally block.

 If an exception occurs, the control flows from the try-to-catch block.

 When an exception occurs in a try block, the appropriate exception object is redirected to
the catch block. This catch block handles the exception according to its statements and
continues the execution.

Syntax

try
{
//Doubtful Statements.
}
2. catch

 The catch block handles the exception raised in the try block.

 The catch block or blocks follow every try block.

 The catch block catches the thrown exception as its parameter and executes the statements
inside it.

 The declared exception must be the parent class exception, the generated exception type in
the exception class hierarchy, or a user-defined exception.

Syntax

try
{
// code
}
catch(Exception e)
{
// code to handle exceptions
}
Example Program

single try-catch block


class Main
{
public static void main(String[] args)
{
try
{
// code that generate exception
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}
In the above code, we have put the "int divideByZero=5/0" in the try block because this statement
must not be executed if the denominator is 0. If the denominator is 0, the statements after this
statement in the try block are skipped. The catch block catches the thrown exception as its
parameter and executes the statements inside it.

Output

ArithmeticException => / by zero

 Multiple catch Blocks

We can use multiple catch statements for different kinds of exceptions that can occur from a single
block of code in the try block.

Syntax

try {
// code to check exceptions
}
catch (exception1) {
// code to handle the exception

}
catch (exception2) {
// code to handle the exception
}
.
.
.
catch (exception n) {
// code to handle the exception
}
Example

public class MultipleCatchBlock {

public static void main(String[] args) {

try {
int x[] = new int[5];
x[5] = 40 / 0;
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception occurs");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBounds Exception occurs");
} catch (Exception e) {
System.out.println("Parent Exception occurs");
}
System.out.println("The program ends here");
}
}
Here, our program matches the type of exception that occurred in the try block with the catch
statements. If the exception that occurred matches any of the usual catch statements, that
particular catch block gets executed.

Output

Arithmetic Exception occurs

The program ends here

 Nested try-catch

Here, we have a try-catch block inside a nested try block.

class NestingTry {
public static void main(String args[]) {
//main try-block
try {
//try-block2
try {
//try-block3
try {
int arr[] = {
10,
20,
30,
40
};
System.out.println(arr[10]);
} catch (ArithmeticException e) {

System.out.print("Arithmetic Exception");

System.out.println(" handled in try-block3");

} catch (ArithmeticException e) {

System.out.print("Arithmetic Exception");

System.out.println(" handled in try-block2");

} catch (ArithmeticException e3) {

System.out.print("Arithmetic Exception");

System.out.println(" handled in main try-block");

} catch (ArrayIndexOutOfBoundsException e4) {

System.out.print("ArrayIndexOutOfBoundsException");

System.out.println(" handled in main try-block");

} catch (Exception e5) {

System.out.print("Exception");

System.out.println(" handled in main try-block");

In the above code, the ArrayIndexOutOfBoundsException occurred in the grandchild try-block3.


Since try-block3 is not handling this exception, the control then gets transferred to the parent try-
block2. Since try-block2 also does not handle that exception, the control gets transferred to the
main try-block, where it finds the appropriate catch block for an exception.

Output

ArrayIndexOutOfBoundsException handled in main try-block

3. finally

The finally block in Java always executes even if there are no exceptions. This is an optional block. It
is used to execute important statements such as closing statements, releasing resources, and
releasing memory. There could be one final block for every try block. This finally block executes after
the try...catch block.

Syntax

try
{
//code
}
catch (ExceptionType1 e1)
{
// catch block
}
finally
{
// finally block always executes
}
Example of Java Exception Handling using finally block

class Main
{
public static void main(String[] args)
{
try
{
// code that generates exception
int divideByZero = 5 / 0;
}
catch (ArithmeticException e)
{
System.out.println("ArithmeticException => " + e.getMessage());
}
finally
{
System.out.println("This is the finally block");
}
}
}
In this Java example, trying to divide by zero results in an ArithmeticException that is caught and
accompanied by an error message. The "finally" block also always runs, printing "This is the finally
block" whether or not an exception was raised.

Output

ArithmeticException => / by zero

This is the finally block

final Vs. finally Vs. finalize in Java

final finally finalize


finally is the block in Java
final is a keyword and access finalize is the method in Java
Exception Handling to
modifier, which is used to apply that is used to perform clean-up
execute the important code
restrictions on a class, method, or processing just before an object
whether the exception occurs
variable. is garbage collected.
or not.
Finally, the block is always
The final keyword is used with the finalize() method is used with
related to the try-catch block
classes, methods, and variables. the objects.
in exception handling.
It is used with variables, methods, It is with the try-catch
Used with objects
and classes. block in exception handling.
Once declared, the final variable
becomes constant and can't be finally block cleans up all the finalize method performs the
modified. A sub-class can neither resources used in the try cleaning concerning the object
override a final method nor can the block before its destruction
final class be inherited.
finally block executes as soon
as the execution of the try-
final method is executed only when finalize method is executed just
catch block is completed
we call it before the object is destroyed
without depending on the
exception
4. throw

 The throw keyword is used to explicitly throw a checked or an unchecked exception.

 The exception that is thrown needs to be of type Throwable or a subclass of Throwable.

 We can also define our own set of conditions for which we can throw an exception explicitly
using the throw keyword.

 The program's execution flow stops immediately after the throw statement is executed, and
the nearest try block is checked to see if it has a catch statement that matches the type of
exception.

Syntax

throw new exception_class("error message");

Example of Exception Handling using Java throw

class ThrowExample {
// Method to check if a number is negative
public static void checkNumber(int number) {
if (number < 0) {
// Throwing an IllegalArgumentException if the number is negative
throw new IllegalArgumentException("Number cannot be negative");
} else {
System.out.println("Number is " + number);
}
}
public static void main(String[] args) {
try {
// Trying to check a negative number
checkNumber(-5);
} catch (IllegalArgumentException e) {
// Handling the thrown exception
System.out.println("Caught an exception: " + e.getMessage());
}
}
}
In the main method, the exception is captured and handled using a try-catch block, showing the
exception message if the input is negative. This Java class, ThrowExample, contains a method
checkNumber that throws an IllegalArgumentException if the input number is negative.

Output

Caught an exception: Number cannot be negative

5. throws

The throws keyword is used in the method signature to indicate that a method in Java can throw
particular exceptions. This notifies the method that it must manage or propagate these exceptions
to the caller.

import java.io.IOException;
public class ThrowsExample {
public static void main(String[] args) {
try {
methodWithException();
} catch (IOException e) {
System.out.println("Caught IOException: " + e.getMessage());
}
}

public static void methodWithException() throws IOException {


// Simulate an IOException
throw new IOException("This is an IOException");
}
}
In the above code, the method methodWithException is declared with throws IOException,
indicating that it may throw an IOException. The catch block catches the IOException in the main
method.

Output

Caught IOException: This is an IOException

throw Vs. throws in Java

throw throws
The throw keyword is used to explicitly Java throws keyword is used in method or function signature
throw an exception inside any block of to declare an exception that the method may throw while
code or function in the program. execution of code
throw keyword can be used to throw both
throws keyword can be used only with checked exceptions.
checked and unchecked exceptions
throw is used within the method. throws is used within the method signature
Syntax: throw new exception_class("error
Syntax: void method() throws ArithmeticException
message");
We can throw only one exception at a We can declare multiple exceptions using the throws
time keyword that the method can throw
Common Scenarios of Java Exceptions

1. ArithmeticException

This exception is raised by JVM when the programmer tries to perform any arithmetic
operation that is not possible in mathematics. One of the frequently occurring arithmetic
exceptions is when we divide any number with zero.

int a=30/0; //ArithmeticException

2. NullPointerException

This occurs when a user tries to access a variable that stores null values. For example, if a variable
stores a null value and the user tries to perform any operation on that variable, a
NullPointerException will be thrown.

String s=null;

System.out.println(s.length());//NullPointerException

3. NumberFormatException

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


a NumberFormatException.

String s="ScholarHat";

int i=Integer.parseInt(s);//NumberFormatException

4. ArrayIndexOutOfBoundsException

When an array exceeds its size, the ArrayIndexOutOfBoundsException occurs.

int a[]=new int[6];

a[10]=80; //ArrayIndexOutOfBoundsException
5. StringIndexOutOfBoundsException

It is the same as ArrayIndexOutOfBoundsException but it is for strings instead of arrays. Here if the
length of a string is less than what we are trying to access there occurs
the StringIndexOutOfBoundsException.

String s = "I am learning Java on ScholarHat.";

System.out.println("String length is:" + s.length());

System.out.println("Length of substring is:" + s1.substring(40)); //StringIndexOutOfBoundsException

Creating own Exception classes

Java allows us to create our own exception class to provide own exception implementation. These
types of exceptions are called user-defined exceptions or custom exceptions.

You can create your own exception simply by extending java Exception class. You can define a
constructor for your Exception (not compulsory) and you can override the toString() function to
display your customized message on catch. Let’s see an example.

Example: Custom Exception

In this example, we are creating an exception class MyException that extends the Java Exception
class and

class MyException extends Exception


{
private int ex;
MyException(int a)
{
ex = a;
}
public String toString()
{
return "MyException[" + ex +"] is less than zero";
}
}

class Demo
{
static void sum(int a,int b) throws MyException
{
if(a<0)
{
throw new MyException(a); //calling constructor of user-defined exception class
}
else
{
System.out.println(a+b);
}
}

public static void main(String[] args)


{
try
{
sum(-10, 10);
}
catch(MyException me)
{
System.out.println(me); //it calls the toString() method of user-defined Exception
}
}
}

OUTPUT

MyException[-10] is less than zero

Example: Custom Exception

Lets take one more example to understand the custom exception. Here we created a class
ItemNotFound that extends the Exception class and helps to generate our own exception
implementation.

class ItemNotFound extends Exception


{
public ItemNotFound(String s) {
super(s);
}

class Demo
{
static void find(int arr[], int item) throws ItemNotFound
{
boolean flag = false;
for (int i = 0; i < arr.length; i++) {
if(item == arr[i])
flag = true;
}
if(!flag)
{
throw new ItemNotFound("Item Not Found"); //calling constructor of user-defined exception
class
}
else
{
System.out.println("Item Found");
}
}

public static void main(String[] args)


{
try
{
find(new int[]{12,25,45}, 10);
}
catch(ItemNotFound i)
{
System.out.println(i);
}
}
}

OUTPUT
ItemNotFound: Item Not Found

You might also like