-
Notifications
You must be signed in to change notification settings - Fork 0
Try‐Catch – Handling Errors Like a Safety Net
Sometimes, things go wrong in a program—just like in real life!
For example:
- You try to divide a number by zero (which is not allowed).
- You ask for a file that doesn’t exist.
- You try to use a Scanner, but the user enters the wrong type of input.
If we don’t handle these errors, our program crashes! 🚨
To prevent crashes, we use try-catch, which acts like a safety net to catch errors and handle them properly.
🔹 try – The code that might cause an error goes inside this block.
🔹 catch – If an error happens, Java jumps here and handles the problem instead of crashing.
📌 Think of it like this:
- Try block: "Let’s try to do something."
- Catch block: "Oops! If something goes wrong, we’ll catch it and handle it."
public class TryCatchExample {
public static void main(String[] args) {
try {
int number = 10 / 0; // This will cause an error!
System.out.println("Result: " + number);
} catch (ArithmeticException e) {
System.out.println("Oops! You can't divide by zero.");
}
System.out.println("Program continues...");
}
}Oops! You can't divide by zero.
Program continues...
🚀 What Happened?
- Java tried to divide 10 by 0 (which is not allowed!).
- Instead of crashing, Java caught the error and printed
"Oops! You can't divide by zero." - The program continues running!
➡️ Without try-catch, the program would have crashed!
Let’s say we ask the user for a number, but they enter a word instead. Normally, the program would crash—but with try-catch, we can handle it!
import java.util.Scanner;
public class TryCatchExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter a number: ");
int number = scanner.nextInt(); // What if the user enters a word?
System.out.println("You entered: " + number);
} catch (Exception e) {
System.out.println("Oops! That's not a number.");
}
System.out.println("Program continues...");
}
}Enter a number: 5
You entered: 5
Program continues...
Enter a number: hello
Oops! That's not a number.
Program continues...
🚀 What Happened?
- If the user enters a number, everything works fine.
- If the user enters a word, Java catches the error and tells them instead of crashing!
Sometimes, different types of errors can happen. We can use multiple catch blocks to handle them separately.
public class MultiCatchExample {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // This will cause an error!
} catch (ArithmeticException e) {
System.out.println("Math error!");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Oops! That index doesn't exist.");
}
}
}Oops! That index doesn't exist.
➡️ Java tried to access numbers[5], but the array only has 3 numbers!
➡️ It caught the correct error (ArrayIndexOutOfBoundsException) and handled it.
Sometimes, we always need to run some code—whether there was an error or not.
📌 Example: Closing a File or Scanner After Using It
import java.util.Scanner;
public class TryCatchFinallyExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter a number: ");
int number = scanner.nextInt();
System.out.println("You entered: " + number);
} catch (Exception e) {
System.out.println("Oops! That's not a number.");
} finally {
scanner.close(); // Always runs to close the scanner
System.out.println("Scanner closed. Program ending.");
}
}
}Enter a number: 10
You entered: 10
Scanner closed. Program ending.
Enter a number: abc
Oops! That's not a number.
Scanner closed. Program ending.
➡️ The finally block always runs!
➡️ We used it to close the scanner (good practice).
| Situation | What Can Go Wrong? | How Try-Catch Helps |
|---|---|---|
| Dividing Numbers | Division by zero crashes the program | Catch the error and show a message |
| Getting User Input | User enters wrong data type | Prevent crash and ask again |
| Reading Files | File might not exist | Handle error and show message |
| Using Arrays | Trying to access an index that doesn’t exist | Avoid crashes and notify user |
That’s try-catch! 🎉