Docsity

Java Exception Handling: Understanding Try, Catch, Finally and Exception Types, Essays (university) of Java Programming

Partial preview of the text

Download Java Exception Handling: Understanding Try, Catch, Finally and Exception Types and more Essays (university) Java Programming in PDF only on Docsity!

Exception handling in java

What is Exception

 (^) An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

Advantages

 (^) Separating Error-Handling Code from "Regular" Code  (^) Propagating Errors Up the Call Stack  (^) Grouping and Differentiating Error Types

Exception Type Hierarchy

Unchecked exceptions

 (^) No need to declare the exception in method’s signature  (^) No compile time checking  (^) Usually indicate programming error  (^) e.g. NullPointerException

Error

 (^) Indicate error in the underlying JVM  (^) Error are external to the application  (^) Application does not usually have to deal with these class of Exceptions  (^) e.g. OutOfMemoryError

What to throw?

 (^) Exceptions v/s Errors  (^) Errors are for JVM  (^) Exceptions for rest of us  (^) Checked v/s Unchecked exceptions  (^) Can caller recover from this error?  (^) Yes: checked  (^) No: unchecked

When to catch exception

  1. When you can handle the exception
  2. When you need to throw a different type of exception
  3. Refer to 1 & 2

3 rules

 (^) What went wrong?  (^) Where did it go wrong?  (^) Why did it go wrong?  (^) If your exception does not provide answers to all these questions, you are doing something wrong!

Performance implications of

exceptions

 (^) Exceptions are expensive for the JVM  (^) Creating stack traces requires resources and CPU  (^) the Java VM requires more efforts to handle a thrown exception than a normal method

Anti Patterns - Log and Throw

 (^) Log the error and throw the same exception again  (^) Messy log file  (^) Achieves nothing

Anti Patterns - Throwing Generic

Exception

 (^) The caller does not know the nature of error – hinders error handling

public SomeInterface buildInstance(String className) { SomeInterface impl = null; try { Class clazz = Class.forName(className); impl = (SomeInterface)clazz.newInstance(); } catch (Exception e) { log.error("Error creating class: " + className); } return impl; }

Anti Patterns - Destructive

Wrapping

catch (NoSuchMethodException e) { throw new MyServiceException("Blah: " + e.getMessage()); }