Handling RuntimeExceptions in Java [closed]

落花浮王杯 提交于 2019-11-29 23:35:55

It doesn't differ from handling a regular exception:

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

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.
}
Ed Altorfer

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 {
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!