allthingsare๐Ÿ…ฟ๏ธ.com Books โฌ…๏ธ Back allthingsare

โ€œDo not wait; the time will never be โ€˜just right.โ€™โ€
[Napoleon Hill (1883โ€“1970) โ€“ American self-help author of Think and Grow Rich]


try-catch-finally


14.1.1 What is an Exception?

In Java, an exception is an unexpected event that interrupts the normal flow of your program.
Examples:

  • Dividing by zero.

  • Accessing an invalid array index.

  • Trying to open a file that doesnโ€™t exist.

If you donโ€™t handle exceptions properly, your program crashes.


Java uses a built-in exception handling system that lets you:

  • Detect problems.

  • Catch them.

  • Handle them gracefully without killing the whole program.


14.1.2 Using try-catch

To handle exceptions, you wrap risky code in a try block.
If something goes wrong, Java jumps to the catch block.

Example:

java
public class TryCatchExample { public static void main(String[] args) { try { int result = 10 / 0; // This will cause an exception System.out.println("Result: " + result); } catch (ArithmeticException e) { System.out.println("Error: Cannot divide by zero."); } } }

How this works:

  • try contains code that might fail.

  • If 10 / 0 happens, an ArithmeticException is thrown.

  • The catch block catches it and prints a safe message.


14.1.3 Adding finally

Sometimes, you need code that always runs, whether an exception happens or not.
This is what finally is for โ€” it runs no matter what.

Example:

java
public class TryCatchFinallyExample { public static void main(String[] args) { try { int[] nums = {1, 2, 3}; System.out.println(nums[5]); // ArrayIndexOutOfBounds } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Invalid index!"); } finally { System.out.println("This runs no matter what."); } } }

Key points:

  • If the try works: the finally runs.

  • If the catch runs: the finally still runs.

  • Good for closing files, releasing resources, or logging.