Java - Exception Hierarchy

1 minute read

All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class.

Errors are not normally trapped form the Java programs. These conditions normally happen in case of severe failures, which are not handled by the java programs. Errors are generated to indicate errors generated by the runtime environment. Example: JVM is out of Memory. Normally programs cannot recover from errors. The only difference between Exception and Error is that you can handle the exception but cannot handle an error.

String-2

Exceptions Methods

Following is the list of important methods available in the Throwable class.

no Methods with Description
1 public String getMessage() Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.
2 public Throwable getCause() Returns the cause of the exception as represented by a Throwable object.
3 public String toString() Returns the name of the class concatenated with the result of getMessage()
4 public void printStackTrace() Prints the result of toString() along with the stack trace to System.err, the error output stream.
5 public StackTraceElement [] getStackTrace() Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.
6 public Throwable fillInStackTrace() Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.
public class Test {

	public static void main(String[] args){
		try{
			int[] a = new int[1];
			a[2] = 5;
		}catch (Exception e) {
			System.out.println(e.getMessage());
			System.out.println("***********************");
			System.out.println(e.getCause());
			System.out.println("***********************");
			System.out.println(e.toString());
			System.out.println("***********************");
			e.printStackTrace();
			System.out.println("***********************");
			System.out.println(e.getStackTrace());
			System.out.println("***********************");
			System.out.println(e.fillInStackTrace());
		}
	}
}
2
***********************
null
***********************
java.lang.ArrayIndexOutOfBoundsException: 2
***********************
java.lang.ArrayIndexOutOfBoundsException: 2
	at Scratch.main(scratch_1.java:6)
***********************
[Ljava.lang.StackTraceElement;@5e2de80c
***********************
java.lang.ArrayIndexOutOfBoundsException: 2

If you liked this article, you can buy me a coffee

Categories:

Updated:

Kumar Rohit
WRITTEN BY

Kumar Rohit

I like long drives, bike trip & good food. I have passion for coding, especially for Clean-Code.

Leave a comment