
- Java.lang - Home
- Java.lang - Boolean
- Java.lang - Byte
- Java.lang - Character
- Java.lang - Character.Subset
- Java.lang - Character.UnicodeBlock
- Java.lang - Class
- Java.lang - ClassLoader
- Java.lang - Compiler
- Java.lang - Double
- Java.lang - Enum
- Java.lang - Float
- Java.lang - InheritableThreadLocal
- Java.lang - Integer
- Java.lang - Long
- Java.lang - Math
- Java.lang - Number
- Java.lang - Object
- Java.lang - Package
- Java.lang - Process
- Java.lang - ProcessBuilder
- Java.lang - Runtime
- Java.lang - RuntimePermission
- Java.lang - SecurityManager
- Java.lang - Short
- Java.lang - StackTraceElement
- Java.lang - StrictMath
- Java.lang - String
- Java.lang - StringBuffer
- Java.lang - StringBuilder
- Java.lang - System
- Java.lang - Thread
- Java.lang - ThreadGroup
- Java.lang - ThreadLocal
- Java.lang - Throwable
- Java.lang - Void
- Java.lang Package Useful Resources
- Java.lang - Useful Resources
- Java.lang - Discussion
Java - RuntimeException
The Java RuntimeException is a subclass of the Exception class. It is an unchecked exception that occurs during the runtime of the program. The RuntimeException class is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine (JVM).
It is part of the java.lang package and is used to indicate that a method has been passed an illegal or inappropriate argument.
It is an unchecked exception, meaning it does not need to be declared in a method's throws clause if it can be thrown by the execution of the method and propagate outside the method boundary.
Hierarchy of RuntimeException
Given below is the class hierarchy of RuntimeException:
java.lang.Object â³ java.lang.Throwable â³ java.lang.Exception â³ java.lang.RuntimeException
Causes of RuntimeException
Following are the reasons when JVM throws a RuntimeException in Java:
- A method has been passed an illegal or inappropriate argument.
- An object is not initialized properly.
- An array is accessed with an illegal index.
- A null object is accessed.
- An invalid type is used in a type cast.
- An invalid operation is performed on a collection, thread, or other object.
- An invalid operation is performed on a file, socket, or other I/O object.
- An invalid operation is performed on a database connection, statement, or result set.
- An invalid operation is performed on a network connection, socket, or other network object.
- An invalid operation is performed on a GUI component, event, or other GUI object.
- An invalid operation is performed on a security manager, policy, or other security object.
- An invalid operation is performed on a class loader, reflection, or other class-related object.
Constructors of RuntimeException
There are two constructors of RuntimeException class:
- RuntimeException(): This constructor is used to create a RuntimeException object without any message.
- RuntimeException(String message): This constructor is used to create a RuntimeException object with a message.
Methods of RuntimeException
There are some methods of RuntimeException class:
Methods of RuntimeException
There are some methods of RuntimeException class:
Modifier | Type | Method | Description |
---|---|---|---|
getMessage() | It is used to return the message of the exception. | ||
toString() | It is used to return the detail message string of the exception. | ||
printStackTrace() | It is used to print the stack trace of the exception. | ||
fillInStackTrace() | It is used to fill in the execution stack trace. | ||
Throwable | getCause() | It is used to return the cause of the exception. | |
Throwable | initCause(Throwable cause) | It is used to initialize the cause of the exception. | |
StackTraceElement[] | getStackTrace() | It is used to return the stack trace of the exception. | |
setStackTrace(StackTraceElement[] stackTrace) | It is used to set the stack trace of the exception. | ||
addSuppressed(Throwable exception) | It is used to add a suppressed exception to the exception. | ||
Throwable[] | getSuppressed() | It is used to return the suppressed exceptions of the exception. | |
printStackTrace(PrintStream s) | It is used to print the stack trace of the exception to the specified print stream. | ||
printStackTrace(PrintWriter s) | It is used to print the stack trace of the exception to the specified print writer. |
Subclasses of RuntimeException
There are many subclasses in RuntimeException. Some of the commonly used subclasses are:
- ArithmeticException: This exception is thrown when an arithmetic operation fails.
- ArrayIndexOutOfBoundsException: This exception is thrown when an array index is out of bounds.
- ClassCastException: This exception is thrown when an object is cast to a class of which it is not an instance.
- IllegalArgumentException: This exception is thrown when a method receives an illegal or inappropriate argument.
- IllegalStateException: This exception is thrown when a method is called at an illegal or inappropriate time.
- IndexOutOfBoundsException: This exception is thrown when an index is out of bounds.
- NegativeArraySizeException: This exception is thrown when an array is created with a negative size.
Example of RuntimeException
In this example, we are trying to divide a number by zero, so JVM will throw a RuntimeException.
public class RuntimeExceptionExample { public static void main(String[] args) { int num1 = 10; int num2 = 0; int result = num1 / num2; // This will throw RuntimeException } }
Output
Following is the output of the above code:
Exception in thread "main" java.lang.ArithmeticException: / by zero at RuntimeExceptionExample.main(RuntimeExceptionExample.java:5)
Example 2 of RuntimeException
In this example, we are trying to access an array element with an invalid index, so JVM will throw a RuntimeException.
public class RuntimeExceptionExample { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; int num = arr[10]; // This will throw RuntimeException } }
Output
Following is the output of the above code:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 5 at RuntimeExceptionExample.main(RuntimeExceptionExample.java:5)
Handling RuntimeException
In this example, we are trying to divide a number by zero, so JVM will throw a RuntimeException. We are handling this exception using try-catch block.
public class RuntimeExceptionExample { public static void main(String[] args) { try { int num1 = 10; int num2 = 0; int result = num1 / num2; // This will throw RuntimeException } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); } } }
Output
Following is the output of the above code:
Cannot divide by zero
How to avoid RuntimeException?
Following are the ways to avoid RuntimeException in Java:
- Always use try-catch block while performing operations that can throw a RuntimeException.
- Always check the input values before performing operations.
- Check the array index before accessing an element.
- Always check the object reference before accessing its methods or properties.
- Always check the type of an object before performing a type cast.
- Always check the state of an object before performing an operation.
- Always check the size of a collection before performing an operation.
- Do not perform operations on a null object.
- Do check the type of an object before performing a type cast.
- Do not perform operations on an invalid type.
Conclusion
In this chapter, we have learned about the RuntimeException class in Java. We have discussed its hierarchy, causes, constructors, methods, subclasses, and how to handle it using try-catch blocks. We have also seen some examples of RuntimeException and how to avoid it.