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 <p><strong>Output:</strong></p> <p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172500564845904.png?x-oss-process=image/resize,p_40" class="lazy" alt="Java RuntimeException" ></p> <p>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.</p> <h4 id="Example-IllegalArgumentException">Example #2 – IllegalArgumentException</h4> <p>The cause of this exception is when the argument format provided is invalid.</p> <p><strong>Code:</strong></p> <pre class="brush:php;toolbar:false">public class Main { inti; public void getMark (int score) { if (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!

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.


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 Linux new version
SublimeText3 Linux latest version

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
