Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Errors are fatalities that we would normally want to cause a program failure, while Exceptions are events that we would normally want to handle in our program. An example of using them with a try-catch statement, a 'try' clause followed by a 'clausecatch' clause:

Code Block
//assert 1 == 0 //AssertionError when uncommented

//try{ assert 1 == 0 }catch(e){}
    //AssertionError when uncommented: Exceptions, not Errors, are caught here

try{
  assert 1 == 0
}catch(Error e){}
    //by specifying Error, prevents bad assertion from causing program failure

try{
  assert 1 == 0
}catch(Throwable e){} //specifying Throwable also prevents program failure

//try{ assert 1 == 0 }catch(Object o){}
    //compile error when uncommented:
    //only Throwables and its subclasses may be caught

...

Code Block
class E1 extends Exception{} //we can define our own exceptions
class E2 extends Exception{}
class E3 extends Exception{}

try{
  def z

  //multi-catch try-block with finally-clause...
  try{
    throw new E2()
    assert false
  }catch(E1 e){
    assert false
    }catch(E2 e){
    z= 'reached here'
    throw new E3() //uncaught exception because only one catch clause executed
  }catch(E3 e){
    assert false //never reached
  }finally{
    assert z == 'reached here'
    throw new E1()
    assert false
  }

}catch(E1 e){} //catches exception thrown in embedded finally clause

...