Java Exceptions Cheat Sheet
What are Exceptions in Java?
In Java, an exception is a problem that arises during the execution of a program. It could occur for various reasons, such as accessing a file that doesn't exist, dividing by zero, or trying to access an element out of bounds in an array. Exceptions disrupt the normal flow of the program and need to be handled properly.
How are Exceptions Handled?
Exceptions are handled using try, catch, and finally blocks in Java.
- try: The code that may throw an exception is contained within a try block.
- catch: If an exception occurs within the try block, it's caught by one or more catch blocks that handle the specific type of exception.
- finally: The finally block is used to execute cleanup code, regardless of whether an exception occurred or not. It's optional and can be omitted if not needed.
Exceptions Example
Java
Copy
import java.util.Scanner; public class ExceptionExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter the numerator:"); int numerator = scanner.nextInt(); System.out.println("Enter the denominator:"); int denominator = scanner.nextInt(); try { // Division operation that might throw an exception int result = numerator / denominator; System.out.println("Result: " + result); } catch (ArithmeticException e) { // Catch block to handle the ArithmeticException System.out.println("Error: Cannot divide by zero!"); } finally { // Cleanup code (optional) scanner.close(); System.out.println("Scanner closed."); } } }
Exception Hierarchy
- Throwable
- The superclass of all errors and exceptions in Java.
- Error (Unchecked)
- Indicates serious problems that a reasonable application should not try to catch.
- Examples:
- OutOfMemoryError
- StackOverflowError
- VirtualMachineError
- Exception (Checked)
- A class representing conditions that a reasonable application might want to catch.
- Subclasses:
- Checked Exceptions
- Must be either caught or declared in the throws clause.
- Examples:
- IOException
- SQLException
- ClassNotFoundException
- Unchecked Exceptions
- Runtime exceptions, not required to be caught or declared.
- Examples:
- NullPointerException
- ArrayIndexOutOfBoundsException
- IllegalArgumentException
Types of Java Exceptions
Java exceptions can broadly be categorized into two main types: checked exceptions and unchecked exceptions.
-
Checked Exceptions:
- Checked exceptions are exceptions that are checked at compile-time by the compiler. This means that the compiler forces the programmer to handle these exceptions explicitly, either by catching them using a try-catch block or by declaring them in the method signature using the throws keyword.
- Examples of checked exceptions include IOException, FileNotFoundException, ClassNotFoundException, SQLException, etc.
- Unchecked Exceptions:
- Unchecked exceptions, also known as runtime exceptions, are exceptions that are not checked at compile-time by the compiler. These exceptions occur at runtime and do not need to be explicitly handled by the programmer. However, it is still a good practice to handle them when appropriate.
- Examples of unchecked exceptions include NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException, NumberFormatException, IllegalArgumentException, etc.
Java Exception Keywords
- try:
The try block is used to enclose the code that might throw an exception. It is followed by one or more catch blocks or a finally block (or both). - catch:
The catch block is used to catch and handle exceptions thrown within the corresponding try block. It specifies the type of exception it can catch and the code to execute if that exception occurs. - finally:
The finally block is used to execute cleanup code that should always run, regardless of whether an exception occurs or not. It's typically used to release resources (like closing files or database connections) that were acquired in the try block. - throw:
The throw keyword is used to explicitly throw an exception. It's typically used when a specific condition is met and the program needs to raise an exception to indicate an error condition. - throws:
The throws keyword is used in method declarations to indicate that the method might throw certain types of exceptions. It specifies the types of exceptions that the method can throw, allowing the caller to handle them appropriately or propagate them further. - try-with-resources:
Introduced in Java 7, the try-with-resources statement is used to automatically close resources that are declared inside the parentheses of the try statement. Resources such as file streams or database connections that implement the AutoCloseable interface are automatically closed when the try block exits, either normally or due to an exception.
List of most common Java Exceptions
- ArithmeticException:
Occurs when an arithmetic operation (like division) results in an error. - NullPointerException:
Occurs when trying to access or call methods on an object reference that points to null. - ArrayIndexOutOfBoundsException:
Occurs when trying to access an array element with an invalid index. - IndexOutOfBoundsException:
Generalized version of ArrayIndexOutOfBoundsException, occurs when trying to access a collection with an invalid index. - NumberFormatException:
Occurs when trying to convert a string to a numeric format, but the string does not contain a valid numeric value. - FileNotFoundException:
Occurs when trying to access a file that does not exist. - IOException:
Generalized exception for input/output errors, including file handling operations. - ClassNotFoundException:
Occurs when trying to load a class dynamically using its name, but the class is not found in the classpath. - NoSuchElementException:
Occurs when attempting to access elements from a data structure like java.util.Scanner, but no more elements are available. - ConcurrentModificationException:
Occurs when trying to modify a collection while iterating over it using an iterator. - UnsupportedOperationException:
Occurs when an unsupported operation is performed on a collection, such as trying to modify an immutable list. - IllegalArgumentException:
Occurs when passing an illegal argument to a method, such as passing a negative value to a method that expects a positive value. - IllegalStateException:
Occurs when the state of an object is not as expected for the operation being performed, such as calling a method on an object in an invalid state. - SecurityException:
Occurs when a security violation is detected, such as attempting to perform an operation that is not allowed by the security manager. - InterruptedException:
Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted. - ClassCastException:
Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. - SQLException:
Thrown when a database access error occurs.
Java Exception Propagation
Exception propagation in Java refers to the process of an exception being thrown by a method and then propagated up the call stack until it is caught and handled or until it reaches the top level of the program.
Example
Java
Copy
public class ExceptionPropagationExample { // Method that throws an exception public static void method1() throws Exception { System.out.println("Inside method1"); // Simulating an exception throw new Exception("Exception in method1"); } // Method that calls method1 public static void method2() throws Exception { System.out.println("Inside method2"); // Calling method1 method1(); } // Main method that calls method2 public static void main(String[] args) { try { System.out.println("Inside main method"); // Calling method2 method2(); } catch (Exception e) { System.out.println("Exception caught in main method: " + e.getMessage()); } } }
Custom Exceptions
Creating a Custom Exception
Java
Copy
public class MyCustomException extends Exception { public MyCustomException(String message) { super(message); } }
Throwing a Custom Exception
Java
Copy
public void myMethod() throws MyCustomException { throw new MyCustomException("Custom error message"); }