Python Try Except

What is try…except?

The try…except block is used to handle exceptions (errors) that occur during the execution of a program. The code inside the try block is executed first. If an error occurs, the execution jumps to the except block where the error is handled.

Key Points:

  • Prevents your program from crashing due to runtime errors.
  • Provides a way to gracefully manage exceptions and execute alternate code.
  • Helps in debugging by allowing custom error messages.

Syntax of try…except

The basic syntax is as follows:

try:
# Code that might raise an exception
risky_code()
except:
# Code to handle the exception
handle_error()

How try…except Works

  1. Python executes the code inside the try block.
  2. If no errors occur, the except block is skipped.
  3. If an error occurs, Python immediately stops executing the try block and moves to the except block.
  4. After handling the exception, the program continues execution.

Examples of try…except

Basic Example:

try:
result = 10 / 0 # This will raise a ZeroDivisionError
except:
print("An error occurred. You cannot divide by zero.")

Output:

An error occurred. You cannot divide by zero.

Handling Specific Exceptions

You can catch specific types of errors by specifying the exception name in the except block.

try:
num = int(input("Enter a number: "))
print("You entered:", num)
except ValueError:
print("Invalid input! Please enter a valid number.")

Output (if user inputs a non-integer):

Invalid input! Please enter a valid number.

Using Multiple except Blocks

You can handle different types of exceptions separately by using multiple except blocks.

try:
num = int(input("Enter a number: "))
result = 100 / num
print("Result:", result)
except ValueError:
print("Error: Invalid input! Please enter a number.")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")

Using else with try…except

An else block can be added after the except block. The code in the else block will only execute if no exceptions are raised in the try block.

try:
num = int(input("Enter a number: "))
result = 100 / num
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Please enter a valid number.")
else:
print("Result is:", result)

Using finally with try…except

The finally block is used to execute code that must run regardless of whether an exception occurred or not. It’s typically used for cleanup actions like closing files or releasing resources.

try:
file = open("example.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
print("Error: File not found.")
finally:
file.close()
print("File closed.")

Nested try…except Blocks

You can use nested try…except blocks for more granular error handling.

try:
try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("Error: You cannot divide by zero.")
except ValueError:
print("Error: Invalid input! Enter a number.")

Common Exceptions in Python

Here are some common exceptions you may encounter:

ExceptionDescription
ValueErrorRaised when a function gets an argument of the correct type but inappropriate value.
ZeroDivisionErrorRaised when dividing by zero.
FileNotFoundErrorRaised when a file is not found.
TypeErrorRaised when an operation is performed on an incompatible type.
IndexErrorRaised when accessing an out-of-range index in a list or tuple.

Best Practices for Using try…except

Handle Specific Exceptions:
Always catch specific exceptions rather than a generic except: block. This makes your code easier to debug.

# Bad practice:
try:
risky_code()
except:
print("Something went wrong.")
# Good practice:
try:
risky_code()
except ValueError:
print("A ValueError occurred.")

Use finally for Cleanup:
Always use the finally block for essential cleanup operations, like closing files or releasing resources.

Avoid Silencing Errors:
Do not use empty except blocks as they can hide critical issues in your code.

# Bad practice:
try:
risky_code()
except:
pass

Log Errors for Debugging:
Log exceptions for better traceability during development.

try:
risky_code()
except Exception as e:
print("Error:", e)

Leave a Comment