Home > Java > javaTutorial > Java RuntimeException

Java RuntimeException

WBOY
Release: 2024-08-30 16:14:06
Original
319 people have browsed it

Exceptions are the ones thrown when any error is encountered while running a code in Java. RuntimeException in java is the one which is called the parent class of all the exceptions in the Java programming language, which will either crash or break down during the execution of the program or the application as and when they occur. But as compared to other exceptions, these are different and cannot be caught by specifying in the code like for others.

Working of RuntimeException in Java

It belongs to the parent class of Exception in the order of Object -> Throwable -> Exception ->RuntimeException. Hence it can be called as the superclass of all the exceptions which can be thrown while running the regular operations of the JVM (Java Virtual Machine). This RuntimeException and its subclasses come under a class of exceptions called “unchecked exceptions”. These cannot and need not be specified in the constructor’s or the method’s clause.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Constructors of RuntimeException in Java

Below are the constructors of RuntimeException:

1. RuntimeException (): This throws us the new runtime exception having its detailed message as null.

Syntax:

public RuntimeException()
Copy after login

The cause here will not be initialized and can be done by calling to the class Throwable.initCause (java.lang.Throwable).

2. RuntimeException (String msg): This also throws a new runtime exception but has the defined detail message we have provided in the Java code.

Syntax:

public RuntimeException (String msg)
Copy after login

Same as the above function, the cause will not be initialized by default, and the same can be done by calling Throwable.initCause (java.lang.Throwable). The msg here is the detail message, which will be saved to retrieve later by the Throwable.getMessage () method.

3. RuntimeException (String msg, Throwable cause): This throws a new runtime exception with the defined error message and its cause.

Syntax:

public RuntimeException (String message, Throwable cause)
Copy after login

Note that the msg here is not automatically included and has to be specified explicitly. Here, the cause is fetched from the Throwable.getCause () function, and here a null value is allowed, which symbolises that its cause does not exist or is unknown.

4. RuntimeException (String msg, Throwable cause, booleanenableSupp, booleanwritableStack): This gives a new runtime exception with the described error message in detail, its specific cause, enableSupp representing whether its suppression has been enabled or disabled, and the writableStack being its stack trace if it is enabled or disabled.

Syntax:

protected RuntimeException (String message,
Throwable cause,
booleanenableSuppression,
booleanwritableStackTrace)
Copy after login

This gives a new runtime exception with the defined cause and a specified detail message, its cause, whether the suppression is enabled or disabled, and if the writable stack trace has been enabled or not. The message here is the specific message we are displaying, the cause indicating whether it exists or not, enableSuppression indicates whether suppression is allowed or not, and writableStackTrace specifies whether the stack trace should be writable or not.

5. RuntimeException (Throwable cause): This throws a new runtime exception with the given cause and specified detailed error message of the condition (cause==null ? null : cause.toString ()), which basically has the class and its particular cause message.

Syntax:

public RuntimeException (Throwable cause)
Copy after login

The cause is kept for later fetching by the Throwable.getCause () method, and when a null value is permitted, it indicates that its cause is not known.

How to Avoid RuntimeException in Java?

The method we do to avoid such exceptions is called exception handling. It is one of the most fundamental things a developer should keep in mind while coding as the entire code will be useless if an exception occurs and if it cannot handle the same.

We use certain clauses called the throw and throw to handle checked exceptions in Java. Runtime exceptions usually occur because of the input being given faulty and cause exceptions like ArrayIndexOutOfBoundsException, IllegalArgumentException, NumberFormatException or a NullPointerException. Including these errors in code, handling does not make any change, but it can be used for the aske of documentation as a good practice.

We can custom define a Runtime exception as below:

public class AuthenticateUser extends RuntimeException {
public AuthenticateUser (String msg) {
super (msg);
}
}
Copy after login

Examples

Below are the examples of 4 major kinds of Runtime exceptions:

Example #1 – ArrayIndexOutOfBoundsException

This occurs when we request an index value of an array that is invalid or not available.

Code:

public class Main
{
public static void main (String[] args)
{
// Random array of numbers
intip[] = {16, 17, 18, 19, 20};
for (inti=0; i<=ip.length; i++)
System.out.println (ip[i]);
}
}
Copy after login

Output:

Java RuntimeException

As seen in this example, in the input array has its index value from 0 to 4. But in this for loop, the length of the array retrieved will be 5, and when that is tried to access in the array, it will throw the ArrayIndexOutOfBoundsException during RunTime of the code.

Example #2 – IllegalArgumentException

The cause of this exception is when the argument format provided is invalid.

Code:

public class Main {
inti;
public void getMark (int score) {
if (score < 0 || score > 100)
throw new IllegalArgumentException (Integer.toString (score));
else
i = score;
}
public static void main (String[] args) {
Main t = new Main ();
t.getMark (30);
System.out.println (t.i);
Main t1 = new Main ();
t1.getMark (120);
System.out.println (t1.i);
}
}
Copy after login

Output:

Java RuntimeException

Here we know that the maximum value of a percentage value is 100. So when we pass the value as 101, we get the Illegal argument exception during run time.

Example #3 – NumberFormatException

This exception is usually thrown when a string is to be converted to a numeric value like either float or integer value, but the form of the string given as input is either illegal or inappropriate.

Code:

public class Main {
// giving input string as null
public static void main (String[] args) {
inti = Integer.parseInt (null);
}
}
Copy after login

Output:

Java RuntimeException

In this example, we are giving the input string to be parsed into an integer as null. Hence the number format exception is thrown.

Example #4 – NullPointerException

This exception occurs when a reference object that the variable is referring to is null.

Code:

public class Main {
public static void main (String[] args) {
Object reference = null;
reference.toString ();
}
}
Copy after login

Output:

Java RuntimeException

In this example, we are creating an object called reference having a null value. The same object is being called for an operation, and hence this error is thrown.

Conclusion: Runtime exceptions are thrown at runtime and hence difficult to be detected during compile time. They are difficult to handle, and the throws clause can only be used to define them but not catch them.

Recommended Article

This is a guide to Java RuntimeException. Here we discuss the Introduction and how to Avoid RuntimeException in Java, and it’s Working along with its examples. You can also go through our other suggested articles to learn more –

  1. Introduction to Heap Sort in Java
  2. Overriding in Java (Examples)
  3. Iterators in C# With Advantages and Disadvantages
  4. Top 10 Java Collection Interview Questions

The above is the detailed content of Java RuntimeException. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template