Exception Handling

Throwable Hierarchy

  • All exceptions in Java must inherit from Throwable class.

  • Error is an exception that unrecoverable e.g. JVM runs out-of-memory
  • Exception is split into two categories
    • Checked exceptions - caught by compiler
    • Unchecked exceptions - inherits from RuntimeException

Chained Exception

  • Throw exception back to the calling method
   // call method2; throw exceptions back to main
   public static void method1() throws Exception
   {
      try 
      { 
         method2(); 
      }
      catch (Exception exception) // exception thrown from method2
      {
         throw new Exception("Exception thrown in method1", exception);
      }
   } // end method method1

Assertions

  • Helps ensure program's validity
    • Pre-condition
    • Post-condition
  • Must be explicitly enabled by -ea in java CLI argument in order to throw an exception
// assert that the value is >= 0 and <= 10
assert (number >= 0 && number <= 10) : "bad number: " + number;

try-with-resources

  • Introduced with Java 7
  • try statement that automatically call close() on an AutoClosable object when try block execution terminates
  • Used for resource de-allocation
try (ClassName theObject = new ClassName())
{
  // Do somehing
}
catch (Exception e)
{
  // Catch exception
}
No Comments
Back to top