Java RuntimeException
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()
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)
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)
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)
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)
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); } }
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]); } }
Output:
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); } }
Output:
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); } }
Output:
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 (); } }
Output:
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 –
- Introduction to Heap Sort in Java
- Overriding in Java (Examples)
- Iterators in C# With Advantages and Disadvantages
- 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip
