How to Throw Runtime Exception in Java

Sheeraz Gul Feb 02, 2024
How to Throw Runtime Exception in Java

This tutorial demonstrates how to throw runtime exceptions in Java.

Throw Runtime Exception in Java

The Runtime Exception is the parent class for all the Java exceptions that cause the program’s crash or breakdown when they occur. The Runtime Exceptions are never checked.

The Runtime Exception is used to show the programmer’s error. These exceptions can also be used when a condition can’t happen.

Java has some of the most used built-in Runtime Exceptions, which include:

  1. ArrayIndexOutOfBoundsException - This runtime exception is thrown when we are trying to access an index of the array which doesn’t exist.
  2. InvalidArgumentException - This runtime exception is thrown when we try to pass an invalid argument to a method of the server connection.
  3. NullPointerException - This runtime exception is thrown when we try to access or use a null value in our code.

The above exception is only a few of the built-in runtime exceptions in Java. Java also has the functionality to create our runtime exception.

Let’s see how to create a runtime exception and throw it into our code.

  1. Create a class that extends the RuntimeException.
  2. Create a constructor method in the class, which will run automatically when our runtime exception is thrown.
  3. Create another class that will be used as the driver class to throw the runtime exception.

Let’s try to implement the above scenario in Java.

package delftstack;

class DemoException extends RuntimeException {
  public DemoException() {
    System.out.println("This is the Demo Runtime Exception!");
  }
}

public class Example {
  public void Throw_RuntimeException() {
    throw new DemoException();
  }
  public static void main(String[] args) {
    try {
      new Example().Throw_RuntimeException();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

The code above creates a custom exception by extending the RuntimeException, and the driver class throws it. See output:

This is the Demo Runtime Exception!
delftstack.DemoException
	at delftstack.Example.Throw_RuntimeException(Example.java:11)
	at delftstack.Example.main(Example.java:15)
Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

Related Article - Java Exception