How to handle the Runtime Exception in Java?


The Runtime Exception is the parent class in all exceptions of the Java programming language that are expected to crash or break down the program or application when they occur. Unlike exceptions that are not considered as Runtime Exceptions, Runtime Exceptions are never checked.

The Runtime Exception usually shows the programmer's error, rather than the condition a program is expected to deal with. Runtime Exceptions are also used when a condition that can't happen. It should be noted that when a program is running out of memory, a program error is thrown instead of showing it as a Runtime Exception.

The most common Runtime Exceptions are NullPointerException, ArrayIndexOutOfBoundsException and the InvalidArgumentException. The Java Virtual Machine throws the first two Runtime Exceptions.

  • The NullPointerException is the exception thrown by the Java Virtual Machine when a user performs some operations on a certain object considered as null or is calling for some method on the null object. A user should not attempt to handle this kind of an exception because it will only patch the problem and not completely fix it.
  • The ArrayIndexOutOfBoundsException is the exception that is automatically thrown by the Java Runtime Environment when a certain Java program incorrectly tries to access a certain location in a set that is non-existent. This often happens when the array index requested is negative, or more than or equal to the array's size. The arrays of Java use the zero-based indexing; thus, the first element of that array has a zero index, the last element comes with an index of size 1, and the nth element comes with an index n-1.
  • The InvalidArgumentException is an exception raised when an invalid parameter is passed to a certain method on the server's referenced connection.

Example

public class MyExceptionTest {
   public void testRuntimeException () {
      throw new MyException();
   }
   public static void main(String[] args) {
      try {
         new MyExceptionTest().testRuntimeException();
      } catch(Exception e) {
         System.out.println(e.getClass().getName());
      }
   }
}
class MyException extends RuntimeException {
   public MyException() {
      super();
   }
}

Output

MyException

Updated on: 06-Feb-2020

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements