What is exception handling in java with example

Bruce 183 Published: 07/13/2024

What is exception handling in java with example

I'd be happy to explain exception handling in Java!

Exception handling in Java refers to the process of catching, processing, and handling unexpected errors or exceptions that occur during the execution of a program. These errors can be runtime errors, such as null pointer exceptions, or logic errors, such as divide-by-zero errors.

In Java, exceptions are represented by classes that extend the java.lang.Throwable class. When an exception occurs, the Java Virtual Machine (JVM) throws an object representing the exception, which is caught and processed by catch blocks in the program.

There are several ways to handle exceptions in Java:

Try-Catch Blocks: The most common way to handle exceptions is to wrap a block of code with a try-catch statement. This consists of: try block: The code that might throw an exception. catch block: Code that will be executed if an exception is thrown in the try block.
    try {

// Code that might throw an exception

int i = Integer.parseInt("Hello");

} catch (NumberFormatException e) {

System.out.println("Caught a NumberFormatException!");

}

Multi-Catch Blocks: Java 7 introduced multi-catch blocks, which allow you to handle multiple exceptions in the same catch block.
    try {

// Code that might throw an exception

} catch (IOException | SQLException e) {

System.out.println("Caught a IOException or SQLException!");

}

Finally Block: A finally block is executed regardless of whether an exception was thrown or not. It's useful for releasing resources like file handles.
    try {

// Code that might throw an exception

} catch (Exception e) {

System.out.println("Caught an Exception!");

} finally {

// This code will be executed, regardless of whether an exception was thrown.

System.out.println("Finally block executed.");

}

Throwing Exceptions: You can also throw your own exceptions using the throw keyword.
    try {

// Code that might throw a custom exception

if (someCondition) {

throw new MyCustomException("Something went wrong!");

}

} catch (MyCustomException e) {

System.out.println("Caught a MyCustomException!");

}

User-Defined Exceptions: You can create your own exception classes by extending the java.lang.Exception class.
    public class MyCustomException extends Exception {

public MyCustomException(String message) {

super(message);

}

}

try {

// Code that might throw a custom exception

if (someCondition) {

throw new MyCustomException("Something went wrong!");

}

} catch (MyCustomException e) {

System.out.println("Caught a MyCustomException!");

}

In summary, Java provides several ways to handle exceptions: try-catch blocks, multi-catch blocks, finally block, throwing your own exceptions, and user-defined exceptions. Understanding these concepts will help you write more robust and reliable code that can effectively recover from errors and unexpected situations!

checked exception in java

I'll make sure to respond in English and provide a detailed explanation of checked exceptions in Java.

Checked exceptions are a type of exception that is explicitly handled by the programmer in Java. Unlike unchecked exceptions, which are not explicitly caught or thrown by the program, checked exceptions must be either caught using a try-catch block or declared to be thrown using an exception handler.

In Java, a checked exception is any exception that is a subclass of the Exception class (but not a subclass of the RuntimeException class). This means that if your code throws a checked exception, you must either catch it with a try-catch block or declare to throw it using an exception handler.

Here are some key characteristics of checked exceptions:

Explicit handling required: Checked exceptions must be explicitly handled by the programmer. If your code throws a checked exception and you don't handle it, the program will not compile. Caught or thrown: Checked exceptions can either be caught using a try-catch block or declared to be thrown using an exception handler.

Subclass of Exception: All checked exceptions are subclasses of the Exception class.

Here is an example of a program that throws a checked exception:

import java.io.FileReader;

import java.io.IOException;

public class CheckedExceptionExample {

public static void main(String[] args) {

try (FileReader reader = new FileReader("file.txt")) { // Try-with-resources statement

int character = reader.read();

System.out.println((char) character);

} catch (IOException e) {

System.err.println("Error reading file: " + e.getMessage());

}

}

}

In this example, the FileReader constructor throws a FileNotFoundException if the file is not found. Because FileNotFoundException is a subclass of Exception, it is a checked exception.

To handle the checked exception, we use a try-catch block with an IOException handler. If the FileReader constructor throws a FileNotFoundException, our program will catch it and print an error message to the console.

By using try-with-resources statement, you can avoid closing resource manually which is good practice in Java.

Here are some best practices for handling checked exceptions:

Don't swallow exceptions: Make sure your exception handler prints the stack trace of the original exception or re-throws it. Use meaningful error messages: Provide context-specific error messages to help users diagnose the problem. Avoid over-handling exceptions: Only catch and handle exceptions that you can meaningfully recover from.

By understanding how checked exceptions work in Java, you can write robust and maintainable code that effectively handles unexpected errors.