- Handling RuntimeExceptions in Java [closed]
- 4 Answers 4
- Java RuntimeException
- Working of RuntimeException in Java
- Constructors of RuntimeException in Java
- How to Avoid RuntimeException in Java?
- Examples
- Example #1 – ArrayIndexOutOfBoundsException
- Example #2 – IllegalArgumentException
- Example #3 – NumberFormatException
- Example #4 – NullPointerException
- Recommended Article
- Please explain RuntimeException in Java and where it should be used
- 2 Answers 2
Handling RuntimeExceptions in Java [closed]
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
I think the non-accepters of SO have figured out by now that those are empty threats. We want mod points!
It’s sad, but I have the impression that obvious 30-second answers to dumb questions usually give more reward points than well-written answers to more interesting questions. For questions with a high view rate, the first answer usually ends up with a lot of reward points even if it is not related to the question at all.
4 Answers 4
It doesn’t differ from handling a regular exception:
try < someMethodThatThrowsRuntimeException(); >catch (RuntimeException ex) < // do something with the runtime exception >
I dont see a problem with this question — I had a Runnable that I suspected was causing a runtime error and I wasn’t aware that you could just wrap any code in a try/catch & add a RunTimeException catch. I Googled’Android handling runtime exceptions’, this was the first question that came up & this answer provided what I needed. Surely thats exactly how SO should work?
If you know the type of Exception that might be thrown, you could catch it explicitly. You could also catch Exception , but this is generally considered to be very bad practice because you would then be treating Exceptions of all types the same way.
Generally the point of a RuntimeException is that you can’t handle it gracefully, and they are not expected to be thrown during normal execution of your program.
Except, perhaps, when a custom component is throwing a RuntimeException because it can not reach a certain host over network and that is crashing your Android app.
You just catch them, like any other exception.
try < somethingThrowingARuntimeException() >catch (RuntimeException re) < // Do something with it. At least log it. >
Not sure if you’re referring directly to RuntimeException in Java, so I’ll assume you’re talking about run-time exceptions.
The basic idea of exception handling in Java is that you encapsulate the code you expect might raise an exception in a special statement, like below.
Then, you handle the exception.
If you need certain things to execute regardless of whether an exception is raised, add finally .
All together it looks like this.
try < // Do something here >catch (AnotherException ex) < >catch (Exception e) < //Exception class should be at the end of catch hierarchy. >finally
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.
Web development, programming languages, Software testing & 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.
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.
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.
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.
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.
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.
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.
public class Main < public static void main (String[] args) < // Random array of numbers intip[] = ; for (inti=0; i >
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.
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); >>
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.
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.
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 –
500+ Hours of HD Videos
15 Learning Paths
120+ Courses
Verifiable Certificate of Completion
Lifetime Access
1000+ Hours of HD Videos
43 Learning Paths
250+ Courses
Verifiable Certificate of Completion
Lifetime Access
1500+ Hour of HD Videos
80 Learning Paths
360+ Courses
Verifiable Certificate of Completion
Lifetime Access
3000+ Hours of HD Videos
149 Learning Paths
600+ Courses
Verifiable Certificate of Completion
Lifetime Access
All in One Software Development Bundle 3000+ Hours of HD Videos | 149 Learning Paths | 600+ Courses | Verifiable Certificate of Completion | Lifetime Access
Financial Analyst Masters Training Program 1000+ Hours of HD Videos | 43 Learning Paths | 250+ Courses | Verifiable Certificate of Completion | Lifetime Access
Please explain RuntimeException in Java and where it should be used
I am following this great discussion at SO, titled: The case against checked exceptions , but I am unable to follow where exactly RuntimeException should be used and how it is different from normal Exceptions and its subclasses. Googling gave me a complex answer, that is, it should be used to deal with programming logic errors and should be thrown when no Exception should normally occur, such as in the default block of switch-case construct. Can you please explain RuntimeException in greater detail here. Thanks.
2 Answers 2
I am unable to follow where exactly RuntimeException should be used
That’s probably because you are looking at an argument, i.e. people are disagreeing about exactly this point.
and how it is different from normal Exceptions and its subclasses.
Very simple: All subclasses of Exception (except for RuntimeException and its subclasses) are checked i.e. the compiler will reject the code unelss you catch or declare them in the method signature. However, subclasses of RuntimeException are unchecked.
Googling gave me a complex answer, that is, it should be used to deal with programming logic errors and should be thrown when no Exception should normally occur, such as in the default block of switch-case construct.
This is the conventional wisdom, which says that for everything that a program can usefully deal with, you should use checked exceptions because then the compiler will force you to deal with them. Conversely, programs can typically not deal usefully with programmer errors, thus they don’t have to be checked. This is how the Java Standard API uses RuntimeException .
The discussion you linked to is sparked by the view of some people (this includes me) who think that checked exceptions lead to bad code and should therefore not be used. Since you can’t disable exception checking in the compiler, the only way to do this is to use only RuntimeException and its subclasses.
One observation that IMO supports this view is that the conventional wisdom of «use unchecked exceptions only for programmer error» is in fact mainly a rationalization of backwards-reasoning: there is no code safety reason why the compiler should not force you to deal with programmer errors. However, something like NullPointerException and ArrayIndexOutOfBoundsException can crop up almost anywhere, and if those were checked, nobody would ever want to program in Java. Thus, the language designers had to make a, huh, exception for those, and make them unchecked. To explain this, they came up with the «unchecked exceptions are for programmer errors» story.