(1) Runtime Exceptions - Part I

We'll try to go deep into java exception handling covering tricky things to gather a clear understanding,but first of all we need to understand the hierarchy of java exceptions. From java.lang -> Object -> Throwable.


  • Throwables that can be included inside a try-catch can be divided like below.But note that you should only catch java.lang.Error at the highest level,even though catching them doesn't make sense in most of the cases.


 
  • Exceptions should handled from narrower to the wider.See a try-catch block as a safe net that tries to catch a bomb which is about to hit the ground and blast.
  



  • These are the only 3 legal formats of try - catch - finally,



  • If you reach try block,then final block would always execute even if there is return in try block,unless you have system.exit() in try block!

  • Q)
public class ExceptionEg {

    int bar() throws NullPointerException{
        throw new IllegalArgumentException();
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.print(new ExceptionEg().bar());
      
        }
what would be the output?
a)compilation error because method does not handle or declare the thrown exception
b)compilation error due to a missing return statement in bar() method
c)compiles fine,but an exception is thrown at runtime.

There we cover very important two points in java.
 
1)Both NullPointerException and IllegalArgumentException are runtime exceptions which do not need to be handled or declared in throws clauses, but are always implied.You ended up in an exception report and not compilation failure.

But the checked exceptions would give compilation errors if not handled.

So,in this Q,not handling the exception thrown,or throwing an exception(IllegalArgumentException) other than what is specified in throws clause(NullPointerException) would not make any compilation errors.(If it was a checked exception,compilation would fail).

2)Then about not returning an int.
It would also not be an issue,because in java,instead of returning you can throw an error.

So the answer is:(c)
  • Under what conditions should actually throw a runtime exception?
When you detect an error with the way your class or method is used, throw a runtime exception.
Generally, there are two categories of situations when you need to throw a runtime exception:

  • Passing invalid parameter values - This is the most common cause of runtime exceptions. Most parameter validation exceptions should be runtime exceptions. Java provides several subclasses to signal these specific problems.
  • Calling methods in a wrong sequence - This is another common cause. When certain methods cannot be called until a class finishes initialization or some other preparatory steps, calls at the wrong time should cause runtime exceptions
Let's talk more about runtime excepitions in part II :)


Next PostNewer Post Home

1 comment: