🚷 Java Exceptions

GunhoΒ·2024λ…„ 10μ›” 18일
1

Object Oriented Programming (OOP) & Java

λͺ©λ‘ 보기
5/29

🚷 Java Exceptions

πŸ’‘ An exception is defined as an event that disrupts the flow of the programme instruction and occurs during the programme execution.

Exception handling can play an important role in enhancing the stability and reliability of programmes.

Java programmatically, defines any Java class that implements the Throwable class as a Java exception. and its hierarchical structure can be graphically illustrated below.

Java exceptions can be largely categorised into three groups:

  • πŸ†˜Β Error
  • πŸ”” Checked Exception (Exception)
  • πŸ”• Unchecked (Runtime) Exception

and all of these have varying implications on application flows regarding their managements.


πŸ†˜Β Error

πŸ†˜ Error is a subclass of Throwable that indicates serious problems that are outside the control of the application and typically cannot be recovered from

Errors in Java often occur from the hardware or OS-related issues and affect the entire flow of a running process or a JVM while the impact of the other exceptions (checked & unchecked) remain at the thread levels.

Some popular Java errors are: OutOfMemoryError, StackOverflowError, InternalError, and UnknownError.


πŸ”” Checked Exception

πŸ”” Checked Exceptions are a type of exception that must be handled at compile time in Java. These include all exceptions that are subclasses of the Exception class, except for subclasses of RuntimeException.

Checked Exceptions often include exceptions where they heavily involve accessing external resources. IOException related to the file executions and SQLException relevant to the database connection could be good examples.

Hence, to enable the compilation to a bytecode file, the source code should either handle the checked exceptions via:

  • try-catch block
  • throws keyword

where these will be discussed in following πŸ•ΈοΈ try-catch-finally and ⚾️ throws/throw sections.


πŸ”• Unchecked (Runtime) Exception

πŸ”• Unchecked Exceptions are a type of exception that occurs during the runtime and hence are not checked at the compile-time by the JVM compiler. These include all exceptions that are subclasses of the RuntimeException class.

Unchecked (Runtime) Exception often occurs as a direct result of human programming errors. IndexoutOfBoundException and Nullpointer Exception could be good examples of unchecked exceptions.

Like checked exceptions, it can be managed via:

  • try-catch block
  • throws keyword

πŸ•ΈοΈ try-catch-finally

In Java, exception handling is primarily done using the try-catch and try-catch-finally structures.

try-catch

In the try-catch structure, the logic becomes placed inside the try block while the exceptions thrown from the try block is handled inside the catch block. If there happens to be no exceptions, then catch block will not be executed.

try {
	// logics
} catch(Exception e) {
	// exception handling
}

In Java, multiple exceptions can occur within a try block, and these exceptions can be handled separately by placing sequential catch blocks. Each catch block is responsible for catching and handling a specified exception.

As a last resort, placing the catch block that handles the parent exception class, the Exception class could be the best practice as all exceptions are the child class of the Exception class and hence, unhandled exceptions will be essentially by the final catch block with the Exception.

If the parent exception (Exception) is placed before the child exceptions, it would catch all exceptions, and the child-specific catch blocks would never be reached.

try {
	// logics
} catch(NullPointerException e) {
	// exception handling
} catch (NumberFormatException e) {
	// exception handling
} catch(Exception e) {
	// exception handling
}

for convenience, multiple exceptions can be also provided in a single block separated by |.

try {
	// logics
} catch(NullPointerException | Exception e) {
	// exception handling
}

try-catch-finally

A finally is a block attached after a try-catch block and no matter the partial result from the try-catch block, finally is a block that always executes.

A finally block is often used to manage the external resources in which methods like close() method, database disconnection and etc can be implemented.

try {
	// logics
} catch(Exception e) {
	// exception handling
} finally {
	// always execute
}

⚾️ throws/throw

throw is a keyword that is used to incur exceptions intentionally. It can be either used within a try block or can come with a throws keyword after a method signature.

throws keyword is an alternative to try-catch blocks for exception handling where the throws transfers its exception handling responsibilities to the method that invoked the method that throws an exception.

Below could be a good example of the use of the throws keyword where the methodA() handles the IOException from the methodB().

public void methodA() {
	try {
    	methodB();
    } catch(IOException e) {
    	e.printStackTrace();
    }
}

public void methodB() throws IOException {
    throw new IOException("IO Exception Occurred");
}

Upon developers' method designs, however, exceptions can be further transferred to the invoking methods where in the below example, presumably, a method calling on methodA() might conduct an exception handling. This approach comes at the cost of increased complexity in a way that from the maintenance perspective, finding a method conducting an exception handling could be difficult.

Hence, a good practice of thethrows keyword is the above where it is directly handled by a method directly invoking the method throwing an exception.

public void methodA() throws IOException {
	methodB();
}

public void methodB() throws IOException {
    throw new IOException("IO Exception Occurred");
}

It may be also noteworthy to point out that multiple exceptions could come with a comma, , for convenience.


public void methodB() throws IOException, NullPointerException, ClassNotFoundException {
...
}

πŸ› οΈ Customised Exceptions

Custom exceptions in Java can be created by extending the Exception class or RuntimeException class, and possibly other subclasses of these classes or the Throwable class. By defining custom exceptions, developers can represent specific error conditions that are more application-specific and domains, thereby enabling more precise and controlled error handling.

Depending on its detailed usability, custom exceptions can either extend checked or unchecked excpetion classes. Below could be good examples.

public class MyCheckedException extends Exception {
    public MyCheckedException(String message) {
        super(message);
    }
}

public class MyUncheckedException extends RuntimeException {
    public MyUncheckedException(String message) {
        super(message);
    }
}

πŸ“š References

μžλ°”μ˜ μ‹ 
Oracle
F-Lab (1)
F-Lab (2)

profile
Hello

0개의 λŒ“κΈ€