Try Except
What Is Try Except?
try-exceptis used to handle errors or exceptions that occur at runtime. Without handling these exceptions, the program could stop abruptly. Usingtry-excepthelps manage these errors and continue running smoothly.
Syntax:
python
try:
# Code that may throw exceptions
statement(s)
except Exception1:
# If Exception1 occurs, this block is executed
statement(s)
except Exception2:
# If Exception2 occurs, this block is executed
statement(s)
else:
# If no exceptions occur, this block is executed
statement(s)
- Include the code that might throw an exception in the
tryblock. - The
exceptblocks handle specific exceptions. - The
elseblock (optional) runs if no exceptions occur.
Examples and Exercises:
- Handling ZeroDivisionError:
This example tries to divide two numbers. If the denominator is zero, it catches the
ZeroDivisionError.pythona = 3 b = 0 c = 0 try: c = a / b except ZeroDivisionError: print('b cannot be zero') print(c)Output:
b cannot be zero 0
- Multiple Except Blocks:
This example handles
ValueErrorandZeroDivisionErrorseparately.pythonx = input('Enter numerator: ') y = input('Enter denominator: ') try: a = int(x) b = int(y) c = a / b except ValueError: print('Check if input string is parsable integer') except ZeroDivisionError: print('Denominator is zero.')Output:
Enter numerator: 25 Enter denominator: 0 Denominator is zero. Enter numerator: 2 5 Enter denominator: 6 Check if input string is parsable integer
- Try-Except with Else Block:
The
elseblock runs if no exceptions are caught.pythonx = input('Enter numerator: ') y = input('Enter denominator: ') try: a = int(x) b = int(y) c = a / b except ValueError: print('Check if input string is parsable integer') except ZeroDivisionError: print('Denominator is zero.') else: print('No Errors.')Output:
Enter numerator: 25 Enter denominator: 5 No Errors. Enter numerator: 2 5 Enter denominator: 5 Check if input string is parsable integer
Exercises:
- Basic Exception Handling:
- Write a function that takes two numbers as input and returns their division. Handle
ZeroDivisionError.
- Write a function that takes two numbers as input and returns their division. Handle
- Multiple Exceptions:
- Modify the function to also handle cases where the input is not a number, catching
ValueError.
- Modify the function to also handle cases where the input is not a number, catching
- Using Else Block:
- Create a function that reads two numbers, divides them, and prints "Success" if no exceptions occur. Use the
elseblock.
- Create a function that reads two numbers, divides them, and prints "Success" if no exceptions occur. Use the
Summary:
try-exceptis essential for handling runtime errors in Python programs. It helps manage exceptions gracefully and ensures the program can continue running or fail gracefully. Practice these concepts to become comfortable with error handling in Python!