Exception Handling in Java
Teaching Notes PPT
Introduction
• Exception = event that disrupts normal flow
• Types: Error, Checked Exception, Unchecked Exception
• Example: Division by zero → ArithmeticException
try – catch
• try block → risky code
• catch block → handles exception
• Flow: JVM jumps to matching catch block
• Example: int a = 5/0;
finally
• Always executes (except [Link] / crash)
• Used for cleanup (closing files, DB connections)
• Executes whether exception occurs or not
throw vs throws
• throw → actually throws exception object
• throws → declares exceptions a method may throw
• throw = action | throws = declaration
try-with-resources
• Introduced in Java 7
• Automatically closes resources
• Works with AutoCloseable classes
• Better than finally for resource cleanup
Built-in Exceptions
• ArithmeticException
• NullPointerException
• ArrayIndexOutOfBoundsException
• NumberFormatException
• IOException, ClassCastException
Creating Custom Exceptions
• Extend Exception (checked) or RuntimeException (unchecked)
• Example: InvalidAgeException extends Exception
• Throw inside program with throw new Exception
Garbage Collection
• JVM reclaims memory of unreachable objects
• Request with [Link]() (not guaranteed)
• Automatic memory management feature
finalize()
• Method called before object GC
• Deprecated and unreliable
• Prefer try-with-resources or Cleaner
Best Practices
• Catch specific exceptions (not just Exception)
• Don’t swallow exceptions silently
• Use try-with-resources
• Preserve cause when rethrowing
Quick Recap Questions
• Difference between throw and throws?
• When does finally not execute?
• Example of checked vs unchecked exception?
• Why is finalize() discouraged?
• Write a program with custom InvalidPasswordException