top of page
hand-businesswoman-touching-hand-artificial-intelligence-meaning-technology-connection-go-

Exploring Java Exceptions

What is Exception?

Let's start with knowing what exceptions are. Java exception is an event that arises during the execution of a program that disrupts the normal flow of the programming of a simple language, they're like red flags when something goes wrong in your code.


Exceptions can be caught and handled by the program. When an exception occurs within a method, it creates an object. This object is called the exception object. It contains information about the exception, such as the name and description of the exception and the state of the program when the exception occurred.


Here are some cases where an exception occurs

  • Code Errors like Null Pointer Exception

  • Network Connection Failure like IOException

  • Invalid Data like NumberFormatException

  • Trying to open a non-existent file like FileNotFoundException

Exception Hierarchy

All Exceptions are subtypes of the java.lang.Exception class. The Exception Class is inherited from the Throwable class. Error is the other class inherited from the Throwable class.




Types of Exceptions:


Exceptions are broadly divided into two categories

  • Checked Exceptions

  • Unchecked Exceptions (Runtime Exceptions)

Checked Exceptions

Checked exceptions are compile-time exceptions. During compilation, the compiler checks for the checked exceptions. If the exception is not appropriately handled, the compiler generates a compilation error.

If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using the throws keyword.


Some examples of Checked exceptions :

  • IOException : Raised when an I/O operation (e.g., reading from or writing to a file) encounters an issue.

  • SQLException: Raised when there is an issue with a database operation.

  • FileNotFoundException: Raised when a file you're trying to access does not exist

  • ClassNotFoundException:Raised when a class that your code tries to load dynamically is not found.


Unchecked Exceptions

Unchecked exceptions are runtime exceptions which are not detected by the compiler. The compiler will not check these exceptions at compile time. In simple words, if a program throws an unchecked exception, and even if we didn’t handle or declare it, the program would not give a compilation error. Usually, the best practice is to specify or catch the exceptions. In Java, exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked.


Some examples of Unchecked exceptions :

  • NullPointerException: Raised when you try to access or manipulate an object that is null.

  • ArrayIndexOutOfBoundsException: Raised when you access an array element using an index that is out of bounds.

  • ArithmeticException: Raised when mathematical operations like division by zero occur.

  • IllegalArgumentException: Raised when an invalid argument is passed to a method.

  • IllegalStateException: Raised when an object is in an inappropriate state for the requested operation.


How to handle exceptions

  • Using try-catch Blocks

    • Surround the code that might throw an exception with a try block.

    • Catch the exception in a catch block and specify the type of exception you want to catch. You can catch multiple exceptions by adding multiple catch blocks.

  • Using finally Blocks

    • The code inside the finally block will always execute, regardless of whether an exception occurred or not.

Example of a try-catch-finally code block.

try {
    // Code that might throw an exception
} catch (ExceptionType e) {
    // Handle the exception
} finally {
    // Cleanup code (e.g., closing resources)
}

  • Throwing Exceptions:

We can throw exceptions explicitly using the throw keyword to create and throw custom exceptions or rethrow exceptions with additional information.


Example of a throw code block.

        if (condition) {
            throw new CustomException("An error occurred.");
		}

  • Using throws Keyword:

The throws keyword in Java is used within a method signature to declare that the method may throw one or more exceptions during its execution. This declaration informs both the compiler and other developers that the method can potentially generate exceptions, but it doesn't handle them within the method. Instead, it transfers the responsibility of handling those exceptions to the caller of the method.


Example of a throw code block

public void readFile(String filename) throws FileNotFoundException,     IOException {
    // Code that might throw FileNotFoundException or IOException
}

Remember, exceptional code isn't about avoiding errors entirely; it's about handling them gracefully when they arise. Exception handling is a crucial aspect of writing resilient and user-friendly Java applications.

Let's handle Exceptions!





37 views0 comments

Kommentare

Mit 0 von 5 Sternen bewertet.
Noch keine Ratings

Rating hinzufügen
bottom of page