What is RuntimeException class?

As known there are two types of Exceptions Checked and Unchecked Exceptions.

Checked Exceptions are exceptions which are derived from java.lang.Exception class.
Checked Exceptions either need to be enclosed with try and catch block or use throws to further throw the Exception.

Unchecked Exceptions are exceptions which are derived from java.lang.RuntimeException class.
Unlike Checked Exceptions, Unchecked Exceptions does not need try/catch block or throws keyword.

RuntimeException
Relation between Exception classes

Below is an example, showing the exception class inheriting from RuntimeException class.

class SomeRuntimeException extends RuntimeException
{
	SomeRuntimeException(String msg)
	{
		super(msg);
	}
}

public class UnCheckedExceptionExample {
	public static void main(String args[])
	{
	int val = 0;

	System.out.println("Before throwing exception");

	if(val == 0)
	{
		throw new SomeRuntimeException("test message");
	}

	System.out.println("After throwing exception");
	}
}

Output:
Before throwing exception
Exception in thread “main” SomeRuntimeException: test message
at UnCheckedExceptionExample.main(UnCheckedExceptionExample.java:18)

You may also like to read:
what is printStackTrace() method
Output printStackTrace() to a String
Purpose of synchronized keyword

3 thoughts on “What is RuntimeException class?”

Leave a Reply