Throwable Class and hierarchy

KyungCheol KohKyungCheol Koh
2 min read

Hello! In this post, i will discuss java. lang.Throwable and the structure of the Throwable class.

Throwable class

The throwable class is the parent or superclass of all errors and exceptions. Thus, it is important that you do not throw Throwable class.

not to do

//Don't do this
public class CustomException extends Throwable {
    private ErrorCode errorCode; 
    private String message;

}

This is a bad practice because Throwable catches all exceptions as well as errors. It is difficult to tell the cause of the errors if you catch the throwable class.

//better than the pervious code
public class CustomException extends RuntimeException {
    private ErrorCode errorCode; 
    private String message;

}

Hierarchy

So how is the throwable class structured?

  • Throwable
    • Error
    • Exception
      • compile checked Exception
      • compile unchecked exception ( during execution) -RuntimeException

Error

Error class is a subclass of Throwable that should not try to catch. Simply put, this is an error that cannot be controlled by developers. One example is OutofMemoryError. These are something that developers cannot control if there have been so many requests that the server cannot handle and spit the error.

Exception

The exception class has two subclasses: Runtime Exceptions and checked Exceptions. Runtime exceptions are thrown during the execution of the application, whereas the checked exception is thrown during the compilation.

One significant difference lies in the semantics of throws. Checked exceptions need to be declared in a method or constructor's throws clause. However, Unchecked exceptions or runtime exceptions do not need to be declared in a method or constructor's throws clause. Thus, you do not use the throws clause for the Runtime exceptions.

Reference

https://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html

0
Subscribe to my newsletter

Read articles from KyungCheol Koh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

KyungCheol Koh
KyungCheol Koh