Java Exceptions occur at run-time, during execution of the program because of unexpected conditions like division by zero, accessing arrays out of bounds, or using null object references, thereby disrupting the usual flow of execution.
Exceptions in Java can occur when there is an unexpected or erroneous situation in the code. They can occur at runtime and can interrupt the normal flow of execution. Various factors, such as input, file system, network, or programming errors, can cause exceptions.
In Java, exceptions are represented by objects that belong to the Exception class or one of its subclasses. When an exception occurs, the Java runtime system creates an exception object and throws it. The code that caused the exception is responsible for catching and handling the exception appropriately.
Exceptions can be thrown explicitly by the code using the throw statement, or they can be thrown implicitly by the runtime system when it encounters an error. When an exception is thrown, the normal flow of execution is interrupted, and the runtime system looks for an exception handler to handle the exception. If no handler is found, the program terminates with an error message. Exceptions in Java can arise for various reasons, such as input/output, arithmetic, and runtime errors. Understanding when and why exceptions arise in Java code sequences is essential for developing robust and error-free Java applications.
In this blog, we will explore the scenarios where exceptions can arise in Java and how to handle them effectively.
What are Exceptions in Java?
Exceptions in Java are errors that occur during program execution, disrupting the normal flow. When an exception occurs, the JVM (Java Virtual Machine) creates an object known as an exception object that contains information about the error, such as the type of exception, the location of the error, and other relevant details. Exception handling is essential to provide error messages, prevent crashes, and identify issues in the code.
In Java, exceptions are two types,
Checked (includes 95% of Java exceptions)
Unchecked (includes 5% of Java exceptions)
Checked Exceptions
In Java, a checked exception is an exception that must be declared in the method signature or handled using a try-catch block. The compiler reviews these exceptions during compilation; the compiler will generate a compilation error if not handled.
Checked exceptions typically occur due to external factors such as network issues, file input/output errors, or database connectivity problems. These exceptions are considered recoverable and should be handled by the programmer.
Example:
Exception
Description
IOException
This exception is thrown when there is an error while interacting with databases, such as connection failures, incorrect SQL statements, or database server errors.
SQLException
This exception is thrown when there is an error while interacting with databases, such as connection failures, incorrect SQL statements, or database server errors.
ClassNotFoundException
This exception is thrown when a class or resource is requested but is not found, such as when a specified class name is misspelled or does not exist.
InterruptedException
This exception is thrown when a thread is interrupted while it is waiting, sleeping, or performing some other blocking operation.
IllegalAccessException
This exception is thrown when an illegal attempt to access a field or method of a class, such as when a private method is called from outside the class.
Unchecked Exception
In Java, an unchecked exception is an exception that is not checked by the compiler at compile-time. These exceptions occur at runtime and are not required to be declared in the method signature or handled using a try-catch block.
Unchecked exceptions are typically caused by programming errors such as dividing by zero, accessing a null object reference, or trying to access an array index that is out of bounds. These exceptions are considered non-recoverable and should be avoided by writing robust, error-free code.
Example:
Exceptions
Description
ArithmeticException
This exception is thrown when an arithmetic operation, such as division or modulo, is performed with inappropriate operands, such as dividing by zero.
NullPointerException
This exception is thrown when an attempt is made to access a null object reference, i.e., it has no value assigned to it.
ArrayIndexOutOfBoundsException
This exception is thrown when an attempt is made to access an array element at an index that is out of the array's bounds.
IllegalArgumentException
This exception is thrown when an illegal argument is passed to a method, such as passing a negative number to a method that requires a positive number.
ClassCastException
This exception is thrown when an attempt is made to cast an object to an incompatible class, i.e., when the object's class is not a subclass of the target class.
Exception Class Hierarchy in Java
How to Resolve Exceptions in Code Sequence in Java?
To resolve exceptions in Java, you need to identify the cause of the exception and then take appropriate action to handle it. Here are some steps you can follow:
Identify the type of exception: When an exception occurs, Java provides a stack trace that gives you information about the kind of exception and the line of code that caused it. You can use this information to identify the type of exception that occurred.
Understand the cause of the exception: Once you have identified the exception type, you must understand why it occurred. This may involve looking at the code that caused the exception, examining the input or data used, or checking external factors like a file or network access.
Handle the exception: Depending on the type and cause of the exception, you will need to handle it appropriately. This could involve retrying an operation, displaying an error message to the user, logging the error for later analysis, or terminating the program gracefully.
Use try-catch blocks: In Java, you can handle exceptions using try-catch blocks. The code that may throw an exception is placed inside the try block, and the code that handles the exception is placed inside the catch block. You can catch specific types of exceptions and take appropriate action based on the type of exception that occurred.
Example code:
import java.util.Scanner;
public class ExceptionExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int x, y, result;
try {
// code that may throw an exception
System.out.print("Enter the value of x: ");
x = scanner.nextInt();
System.out.print("Enter the value of y: ");
y = scanner.nextInt();
result = x / y;
System.out.println("Result: " + result);
} catch (Exception e) {
System.out.println("Exception: ");
e.printStackTrace();
}
// code to be executed regardless of whether an exception was thrown or not
finally {
System.out.println("Program complete.");
}
}
}
You can also try this code with Online Java Compiler
Enter the value of x: 3
Enter the value of y: 0
Exception:
java.lang.ArithmeticException: / by zero
at ExceptionExample.main(Main.java:19)
Program complete.
Note: finally(): the finally{..} block is used to define a code section that should be executed regardless of whether an exception was thrown or not in a try-catch block.
Now, we will discuss a few examples of exception handling. You can refer to these for a better understanding
ArithmeticException
This exception is thrown when an arithmetic operation produces an error, such as dividing by zero. Here's an example:
public class Example1 {
public static void main(String[] args) {
int num1 = 10;
int num2 = 0;
try {
int result = num1 / num2;
}
catch (ArithmeticException e) {
System.out.println("Division by zero.");
}
}
}
You can also try this code with Online Java Compiler
In this example, an attempt is made to divide num1 by num2, which is zero. This results in an ArithmeticException, which is caught by the try-catch block and handled appropriately.
NullPointerException
This exception is thrown when a null reference is used where an object is expected. Here's an example:
public class Example2 {
public static void main(String[] args) {
String str = null;
try {
int length = str.length();
}
catch (NullPointerException e) {
System.out.println("Null reference.");
}
}
}
You can also try this code with Online Java Compiler
In this example, the length() method is called on a null reference, resulting in a NullPointerException. The exception is caught by the try-catch block and handled appropriately.
ArrayIndexOutOfBoundsException
This exception is thrown when an attempt is made to access an array element that does not exist. Here's an example:
public class Example3 {
public static void main(String[] args) {
int[] nums = {1, 2, 3};
try {
int num = nums[3];
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds.");
}
}
}
You can also try this code with Online Java Compiler
In this example, an attempt is made to access the fourth element of the nums array, which does not exist. This results in an ArrayIndexOutOfBoundsException, which is caught by the try-catch block and handled appropriately.
IOException
This exception is thrown when an input/output operation fails, such as reading from a file that does not exist. Here's an example:
public class Example4 {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("file.txt");
int c = reader.read();
reader.close();
}
catch (IOException e) {
System.out.println("Failed to read file.");
}
}
}
You can also try this code with Online Java Compiler
In this example, an attempt is made to read from a file that does not exist, resulting in an IOException. The exception is caught by the try-catch block and handled appropriately.
SQLException
This exception is thrown when a database access error occurs, such as an invalid SQL query. Here's an example:
public class Example5 {
public static void main(String[] args) {
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test",
"user", "pass");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM table");
conn.close();
}
catch (SQLException e) {
System.out.println("Failed to execute SQL query.");
}
}
}
You can also try this code with Online Java Compiler
In this example, an attempt is made to execute an invalid SQL query, resulting in an SQLException. The exception is caught by the try-catch block and handled appropriately.
ClassCastException
This exception is thrown when an object is cast to an incompatible class. Here's an example:
public class Example6 {
public static void main(String[] args) {
Object obj = "Hello";
try {
Integer num = (Integer) obj;
}
catch (ClassCastException e) {
System.out.println("Object cannot be cast to Integer.");
}
}
}
You can also try this code with Online Java Compiler
In this example, an attempt is made to cast an object of type String to an Integer, resulting in a ClassCastException. The exception is caught by the try-catch block and handled appropriately.
IllegalArgumentException
This exception is thrown when an illegal argument is passed to a method. Here's an example:
public class Example7 {
public static void main(String[] args) {
try {
int num = Integer.parseInt("abc");
}
catch (IllegalArgumentException e) {
System.out.println("Invalid argument for parseInt method.");
}
}
}
You can also try this code with Online Java Compiler
In this example, an attempt is made to parse a string that is not a valid integer, resulting in an IllegalArgumentException. The exception is caught by the try-catch block and handled appropriately.
FileNotFoundException
This exception is thrown when a file cannot be found. Here's an example:
public class Example8 {
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(new File("file.txt"));
scanner.close();
}
catch (FileNotFoundException e) {
System.out.println("File not found.");
}
}
}
You can also try this code with Online Java Compiler
In this example, an attempt is made to open a file that does not exist, resulting in a FileNotFoundException. The exception is caught by the try-catch block and handled appropriately.
InterruptedException
This exception is thrown when a thread is interrupted while waiting, sleeping, or performing a blocking I/O operation. Here's an example:
In this example, a thread is created that sleeps for one second. Another thread waits for the first thread to finish using the join method. If the first thread is interrupted while sleeping, an InterruptedException is thrown and caught by the try-catch block.
OutOfMemoryError
This error is thrown when there is insufficient memory to allocate an object. Here's an example:
public class Example10 {
public static void main(String[] args) {
try {
byte[] bytes = new byte[Integer.MAX_VALUE];
}
catch (OutOfMemoryError e) {
System.out.println("Not enough memory to allocate byte array.");
}
}
}
You can also try this code with Online Java Compiler
In this example, an attempt is made to allocate an array too large to fit in memory, resulting in an OutOfMemoryError. The error is caught by the try-catch block and handled appropriately.
Note: Errors are not exceptions but can still be caught in a try-catch block.
What is the purpose of exception handling in Java?
The purpose of exception handling in Java is to provide a way to gracefully handle errors and unexpected situations that can occur during the execution of a program. Exceptions, on the other hand, are problems that the program can handle.
What is the difference between an error and an exception in Java?
Errors in Java are serious problems that usually cannot be recovered from. Examples include OutOfMemoryError and StackOverflowError. Exceptions, on the other hand, are problems that can be handled by the program.
Can you have multiple catch blocks in Java?
Yes, you can have multiple catch blocks in Java. The catch blocks are evaluated in order, and the first catch block that matches the thrown exception type is executed.
What happens if an exception is not caught in Java?
If an exception is not caught in Java, it will propagate up the call stack until a catch block catches it or the program terminates. If the exception is not detected, the program will terminate abnormally.
Conclusion
In this article, we discussed exceptions in Java. We discussed different types of exceptions and when they arise. Further, we discussed a few examples of exception handling.