In this lesson, you will learn
The exception hierarchy in Java is rooted in the java.lang.Throwable
class, which is divided into two main subclasses: Error
and Exception
.
This hierarchy is essential for understanding how exceptions are handled and how to create custom exceptions.
It has two subclasses
RuntimeException
).OutOfMemoryError
and StackOverflowError
.
throws
clause.Exception
class (excluding RuntimeException
).IOException
is a checked exception. If you’re reading a file from a disk, you must handle or declare IOException
to deal with potential IO problems.try-catch
block or declared them in the method’s throws
clause.IOException
: Thrown during input/output operations.FileNotFoundException
: Thrown when a file is not found.SQLException
: Thrown during database access.ClassNotFoundException
: Thrown when a class cannot be found.InterruptedException
: Thrown when a thread is interrupted.
It is mandatory for a programmer to handle the checked exceptions If not handled, then a compile-time error occurs.
The checked exceptions are the objects of the Exception class or any of its subclasses excluding the RuntimeException and Error class.
There are two main methods to handle checked exceptions:
throws
clause is used in a method’s declaration to indicate that the method may throw one or more exceptions.
public returnType methodName(parameters) throws ExceptionType1,
ExceptionType2 {
// Code that might throw an exception
}
Consider the following example where the readLine()
method is used to take input using the BufferedReader class.
package ch12.l5;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class CheckedExceptionExample1 {
public static String isEven(int number) {
return number%2==0?"Even":"Odd";
}
public static void main(String[] args) {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Enter any number: ");
int x = Integer.parseInt(br.readLine());
System.out.println("x is "+isEven(x)+" number");
}
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type IOException
at jcodebook
ch12.l5.CheckedExceptionExample1.main(CheckedExceptionExample1.java:16)
The above program displays a compilation error because the readLine() method throws a checked exception i.e. IOException
which must be handled explicitly in the program.
Here’s an example of declaring a method that might throw an IOException
, which is a checked exception. The calling method is responsible for handling this exception.
package ch12.l5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CheckedExceptionExample1 {
public static String isEven(int number) {
return number%2==0?"Even":"Odd";
}
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Enter any number: ");
int x = Integer.parseInt(br.readLine());
System.out.println(x+" is a "+isEven(x)+" number");
}
}
Test Case-1:
Enter any number:
9
9 is a Odd number
Test Case-2:
Enter any number:
12
12 is a Even number
try-catch
block is used to catch and handle exceptions.try
block, execution is transferred to the corresponding catch
block where that exception type is specified.
try {
// Code that might throw an exception
} catch (ExceptionType name) {
// Code to handle the exception
}
package ch12.l5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CheckedExceptionExample2 {
public static String isEven(int number) {
return number%2==0?"Even":"Odd";
}
public static void main(String[] args) {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Enter any number: ");
int x=0;
try {
x = Integer.parseInt(br.readLine());
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(x+" is a "+isEven(x)+" number");
}
}
Test Case-1:
Enter any number:
9
9 is a Odd number
Test Case-2:
Enter any number:
12
12 is a Even number
Below is a summary table of some commonly encountered checked exceptions in Java with a brief description for each.
Exception Class | Package | Description |
---|---|---|
IOException | java.io |
General class for I/O-related failures. |
FileNotFoundException | java.io |
Thrown when a file specified by a pathname does not exist. |
SQLException | java.sql |
Represents database access errors or other errors related to database operations. |
ClassNotFoundException | java.lang |
Thrown when an application tries to load a class by name and the class cannot be found. |
ParseException | java.text |
Thrown when parsing operations fail. |
MalformedURLException | java.net |
Thrown to indicate a malformed URL has occurred. |
NoSuchMethodException | java.lang |
Thrown when a requested method could not be found. |
InterruptedException | java.lang |
Thrown when a thread is interrupted while it is waiting, sleeping, or doing another operation. |
RuntimeException
class.ArithmeticException
is an unchecked exception that might occur when dividing a number by zero.NullPointerException
: Thrown when accessing a null object.ArrayIndexOutOfBoundsException
: Thrown when accessing an invalid array index.ArithmeticException
: Thrown during arithmetic errors (e.g., division by zero).IllegalArgumentException
: Thrown when a method receives an invalid argument.ClassCastException
: Thrown during invalid type casting.
ArithmeticException
An ArithmeticException
can occur during arithmetic operations, for example, when dividing by zero. Catching this exception can help handle mathematical errors gracefully.
public class ArithmeticExceptionHandling {
public static void main(String[] args) {
try {
int result = 10 / 0;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException:
Cannot divide by zero.");
}
}
}
Caught ArithmeticException: Cannot divide by zero.
NullPointerException
A NullPointerException
occurs when an application attempts to use null
in a case where an object is required. Catching this exception can prevent the application from crashing when accessing null references.
public class NullPointerExceptionHandling {
public static void main(String[] args) {
String text = null;
try {
System.out.println(text.length());
} catch (NullPointerException e) {
System.out.println(e);
}
}
}
Output
java.lang.NullPointerException: Cannot invoke "String.length()" because "text" is null
Below is a summary table of some commonly encountered unchecked exceptions in Java. These exceptions are inherited from java.lang.RuntimeException
and are not required to be caught or declared thrown by a method.
Exception Class | Description |
---|---|
NullPointerException | Thrown when an application attempts to use null where an object is required. |
ArrayIndexOutOfBoundsException | Thrown to indicate that an array has been accessed with an illegal index. |
ClassCastException | Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. |
IllegalArgumentException | Thrown to indicate that a method has been passed an illegal or inappropriate argument. |
ArithmeticException | Thrown when an exceptional arithmetic condition has occurred (e.g., division by zero). |
NumberFormatException | Thrown to indicate that the application has attempted to convert a string to a numeric type, but the string does not have the appropriate format. |
IllegalStateException | Thrown to indicate that a method has been invoked at an illegal or inappropriate time. |
NoSuchElementException | Thrown by various accessor methods to indicate that the element being requested does not exist. |
IndexOutOfBoundsException | Thrown to indicate that an index of some sort (e.g., array, string) is out of range. |
UnsupportedOperationException | Thrown to indicate that the requested operation is not supported. |
ConcurrentModificationException | Thrown by methods that have detected concurrent modification of an object when such modification is not permissible. |
SecurityException | Thrown by the security manager to indicate a security violation. |
Feature | Checked Exceptions | Unchecked Exceptions |
---|---|---|
Compile-time | Checked | Not checked |
Handling | Mandatory | Optional |
Inheritance | Exception (excluding RuntimeException ) |
RuntimeException or Error |
Typical Causes | External factors | Programming errors |
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.