Java provides two main exception types: runtime exceptions and checked exceptions. All checked exceptions extend from java.lang.Exception, while runtime exceptions extend from either java.lang.RuntimeException or java.lang.Error.
For Run time exceptions:
For Run time exceptions:
- method signature does not need to declare runtime exceptions
- caller to a method that throws a runtime exception is not forced to catch the runtime exception
- Runtime exceptions extend from RuntimeException or Error
For Checked exceptions:
- method must declare each checked exception it throws
- caller to a method that throws a checked exception must either catch the exception or throw the exception itself
- Checked exceptions extend from Exception
Checked exceptions indicate an exceptional condition from which a caller can conceivably recover. Runtime exceptions indicate a programmatic error from which a caller cannot normally recover.
Checked exceptions force you to catch the exception and to do something about it. You should always catch a checked exception once you reach a point where your code can make a meaningful attempt at recovery. However, it is best not to catch runtime exceptions. Instead, you should allow runtime exceptions to bubble up to where you can see them.
In order to throw exeption from static block, you have to change MyException to inherit from RuntimeException. In my opinion, this is still not a elegant way.
Checked exceptions force you to catch the exception and to do something about it. You should always catch a checked exception once you reach a point where your code can make a meaningful attempt at recovery. However, it is best not to catch runtime exceptions. Instead, you should allow runtime exceptions to bubble up to where you can see them.
In order to throw exeption from static block, you have to change MyException to inherit from RuntimeException. In my opinion, this is still not a elegant way.
Posted in: