问题
Can anyone explain how to handle the Runtime Exceptions in Java?
回答1:
It doesn't differ from handling a regular exception:
try {
someMethodThatThrowsRuntimeException();
} catch (RuntimeException ex) {
// do something with the runtime exception
}
回答2:
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.
回答3:
You just catch them, like any other exception.
try {
somethingThrowingARuntimeException()
}
catch (RuntimeException re) {
// Do something with it. At least log it.
}
回答4:
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 {
}
来源:https://stackoverflow.com/questions/2028719/handling-runtimeexceptions-in-java