Question

Can anyone explain how to handle the Runtime Exceptions in Java?

Was it helpful?

Solution

It doesn't differ from handling a regular exception:

try {
   someMethodThatThrowsRuntimeException();
} catch (RuntimeException ex) {
   // do something with the runtime exception
}

OTHER TIPS

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.

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.

try {
   // Do something here
}

Then, you handle the exception.

catch (Exception e) {
   // Do something to gracefully fail
}

If you need certain things to execute regardless of whether an exception is raised, add finally.

finally {
   // Clean up operation
}

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 {
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top