Java Tutorial
Operators
Flow Control
String
Number and Date
Built-in Classes
Array
Class and Object
Inheritance and Polymorphism
Exception Handling
Collections, Generics and Enumerations
Reflection
Input/Output Stream
Annotation
Exception handling is a crucial concept in Java programming. It helps you gracefully deal with errors and maintain the normal flow of your program. In this tutorial, we will discuss Java exception handling and explore some common exceptions you may encounter.
a. Checked Exceptions: These are exceptions that must be explicitly caught or declared in a method's throws clause. They usually represent recoverable conditions, such as FileNotFoundException.
b. Unchecked Exceptions: These exceptions are not required to be explicitly caught or declared. They typically represent programming errors, such as NullPointerException.
a. try block: Encloses the code that might throw an exception.
b. catch block: Catches and handles the exception thrown by the try block. You can have multiple catch blocks to handle different exceptions.
c. finally block: Executes regardless of whether an exception is thrown or caught. It is typically used to release resources.
Example:
try { // Code that might throw an exception } catch (ExceptionType1 e) { // Handle ExceptionType1 } catch (ExceptionType2 e) { // Handle ExceptionType2 } finally { // Cleanup code }
a. NullPointerException: Occurs when you try to access a method or field of a null object reference.
b. ArrayIndexOutOfBoundsException: Occurs when you try to access an array element with an index that is out of bounds.
c. FileNotFoundException: Occurs when a file cannot be found or accessed.
d. IOException: Represents an error that occurs during input or output operations, such as reading or writing a file.
e. NumberFormatException: Occurs when trying to parse a string to a numeric type, but the string is not formatted correctly.
f. ArithmeticException: Occurs when an arithmetic operation, such as division by zero, results in an error.
Example:
public class ExceptionHandlingExample { public static void main(String[] args) { try { int[] numbers = {1, 2, 3}; System.out.println(numbers[3]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Array index is out of bounds."); } catch (NullPointerException e) { System.out.println("Null pointer exception occurred."); } finally { System.out.println("This will always execute."); } } }
In this example, an ArrayIndexOutOfBoundsException occurs, so the corresponding catch block is executed. The finally block is executed regardless of the exception.
Example:
class CustomException extends Exception { public CustomException(String message) { super(message); } }
To use the custom exception, you can throw it using the throw
keyword:
public void checkAge(int age) throws CustomException { if (age < 18) { throw new CustomException("Age must be 18 or older."); } }
Remember that understanding and handling exceptions properly can make your code more robust and easier to maintain. Practice and familiarize yourself with common exceptions and how to handle them effectively.
try, catch, and finally blocks in Java
The try
block contains the code that might throw an exception. The catch
block handles the exception, and the finally
block ensures code execution, whether an exception occurs or not.
try { // Code that may throw an exception } catch (ExceptionType ex) { // Handle the exception } finally { // Code to execute regardless of whether an exception occurred }
Common exceptions in Java and their meanings
Common exceptions include NullPointerException
, ArrayIndexOutOfBoundsException
, ArithmeticException
, and FileNotFoundException
. Each indicates a specific error in the code.
try { // Code that may throw exceptions } catch (NullPointerException e) { // Handle null references } catch (ArrayIndexOutOfBoundsException e) { // Handle array index out of bounds } catch (ArithmeticException e) { // Handle arithmetic errors } catch (Exception e) { // Handle other exceptions }
Custom exception handling in Java
You can create custom exceptions by extending the Exception
class. This allows you to define your own exception types.
class CustomException extends Exception { // Custom exception code } try { throw new CustomException(); } catch (CustomException e) { // Handle custom exception }
Checked vs. unchecked exceptions in Java
Checked exceptions are checked at compile time and must be either caught or declared. Unchecked exceptions (RuntimeExceptions) don't require explicit handling.
// Checked exception (must be caught or declared) try { throw new IOException(); } catch (IOException e) { // Handle or declare } // Unchecked exception throw new RuntimeException();
Throwing exceptions in Java with throw
keyword
The throw
keyword is used to explicitly throw an exception.
if (condition) { throw new CustomException(); }
Exception propagation in Java
Exceptions can propagate up the call stack if not caught. Each method in the call stack is given a chance to handle the exception.
public void methodA() { methodB(); } public void methodB() { // Exception occurs here and propagates to methodA if not caught }
Handling multiple exceptions in Java
You can handle multiple exceptions in a single catch
block or use multiple catch
blocks for different exceptions.
try { // Code that may throw exceptions } catch (IOException | SQLException e) { // Handle IOException or SQLException }
Java StackTrace and debugging exceptions
The stack trace provides information about the call stack when an exception occurs. It helps in debugging.
try { // Code that may throw an exception } catch (Exception e) { e.printStackTrace(); }