3.6.2 Exception Handling (try-catch)
3.6.2 Exception Handling (try-catch)
Imagine you're a robot trying to open a file on a computer. What if the file isn't there? Instead of just stopping and saying "Error!", you want the robot to be polite and say, "I couldn't find the file, would you like me to try again?"
Exception Handling is a programming technique that allows your program to gracefully deal with runtime errors (also called "exceptions"). Instead of crashing when something unexpected happens, you can "catch" the error and tell your program what to do about it.
The most common way to do this is using a try-catch block (or try-except in Python).
How try-catch Works:
tryblock:- You put the code that might cause an error inside the
tryblock. - It's like saying, "TRY to do this risky thing."
- You put the code that might cause an error inside the
catchblock (orexceptin Python):- If an error (an "exception") does happen inside the
tryblock, the program immediately jumps to thecatchblock. - The
catchblock contains the code that tells your program how to handle the error. This might involve:- Printing an error message to the user.
- Logging the error for the programmer to see later.
- Trying an alternative action.
- Asking the user for new input.
- You usually specify the type of error you want to catch (e.g., a "file not found" error, or a "division by zero" error).
- If an error (an "exception") does happen inside the
Example (Java concept):
// Imagine we're trying to divide two numbers
int numerator = 10;
int denominator = 0; // Uh oh, this will cause a division by zero error!
try {
// TRY to do this calculation
int result = numerator / denominator;
System.out.println("Result: " + result); // This line won't run if an error happens above
} catch (ArithmeticException e) { // CATCH a specific type of error: ArithmeticException (like division by zero)
// If the error happens, do THIS instead of crashing
System.out.println("Error: Cannot divide by zero!");
// You can also print details about the error:
// System.out.println("Error details: " + e.getMessage());
}
System.out.println("Program continues after the try-catch block.");
// Output:
// Error: Cannot divide by zero!
// Program continues after the try-catch block.
Without the try-catch block, the program would have crashed when it tried to divide by zero. With it, it handles the error gracefully and continues running.
Exception handling is a powerful way to make your programs more robust and user-friendly, preventing unexpected crashes and providing helpful feedback.
Bibliography:
- GeeksforGeeks - Exception Handling in Java: https://www.geekshttps://www.geeksforgeeks.org/java/exceptions-in-java/forgeeks.org/java/exceptions-in-java/
- W3Schools - Python Try Except: https://www.w3schools.com/python/python_try_except.asp
- Wikipedia - Exception handling: https://en.wikipedia.org/wiki/Exception_handling