Try and Except

try and except are used for error handling in Python.
They prevent your program from crashing when an error occurs.

Instead of stopping the program, Python executes the except block.

BASIC SYNTAX

try:
# code that may cause error
except:
# code that runs if error occurs

SIMPLE EXAMPLE

try:
num = int(input("Enter a number: "))
print(10 / num)
except:
print("An error occurred.")

If the user enters 0 or text, the program will not crash.

HANDLING SPECIFIC ERRORS

It is better to handle specific exceptions.

1. ZeroDivisionError

try:
print(10 / 0)
except ZeroDivisionError:
print("You cannot divide by zero.")

2. ValueError

try:
num = int("abc")
except ValueError:
print("Invalid input. Please enter a number.")

MULTIPLE EXCEPT BLOCKS

try:
num = int(input("Enter number: "))
result = 10 / num
except ValueError:
print("Invalid number.")
except ZeroDivisionError:
print("Cannot divide by zero.")

Each error type is handled separately.

USING AS e (SHOW ERROR MESSAGE)

try:
num = int("abc")
except Exception as e:
print("Error:", e)

e stores the actual error message.

TRY – EXCEPT – ELSE

The else block runs if no error occurs.

try:
num = int(input("Enter number: "))
except ValueError:
print("Invalid input.")
else:
print("You entered:", num)

TRY – EXCEPT – FINALLY

The finally block runs no matter what.

try:
print(10 / 2)
except ZeroDivisionError:
print("Error")
finally:
print("Execution completed.")

COMPLETE STRUCTURE

try:
# risky code
except SpecificError:
# handle specific error
except Exception as e:
# handle other errors
else:
# runs if no error
finally:
# always runs

WHY USE TRY & EXCEPT?

• Prevents program crashes
• Makes programs user-friendly
• Handles unexpected situations
• Important for file handling, databases, APIs, etc.

KEY TAKEAWAYS

try contains risky code
except handles errors
else runs if no error
finally always runs
• Handle specific errors when possible

try and except are essential for writing safe and professional Python programs.

Home » PYTHON INTERMEDIATE (PYI) > Exception Handling > Try and Except