Python Try Except

The try...except statement is used to handle errors and prevent a program from crashing. When an error occurs inside the try block, Python executes the except block. Basic Try Except Syntax Example Output: Catch Specific Exceptions Example Output: Multiple Except Blocks Example Output: Using Exception as a Variable Example Output: Try Except Else The else […]

2 mins read Lesson 49 of 56 88% through track

The try...except statement is used to handle errors and prevent a program from crashing. When an error occurs inside the try block, Python executes the except block.

Basic Try Except

Syntax

try:
    # code that may cause an error
except:
    # code to handle the error

Example

try:
    print(10 / 0)
except:
    print("An error occurred")

Output:

An error occurred

Catch Specific Exceptions

Example

try:
    number = int("abc")
except ValueError:
    print("Invalid number")

Output:

Invalid number

Multiple Except Blocks

Example

try:
    number = int("abc")
    print(10 / 0)

except ValueError:
    print("Value Error")

except ZeroDivisionError:
    print("Division by zero")

Output:

Value Error

Using Exception as a Variable

Example

try:
    print(10 / 0)

except Exception as error:
    print(error)

Output:

division by zero

Try Except Else

The else block runs if no exception occurs.

Example

try:
    print(10 / 2)

except ZeroDivisionError:
    print("Error")

else:
    print("Operation successful")

Output:

5.0
Operation successful

Try Except Finally

The finally block always executes, whether an exception occurs or not.

Example

try:
    print(10 / 0)

except ZeroDivisionError:
    print("Cannot divide by zero")

finally:
    print("Execution completed")

Output:

Cannot divide by zero
Execution completed

Complete Example

Example

try:
    num = int(input("Enter a number: "))
    result = 100 / num

except ValueError:
    print("Please enter a valid number")

except ZeroDivisionError:
    print("Number cannot be zero")

else:
    print("Result:", result)

finally:
    print("Program ended")

Summary

  • try contains code that may cause an error.
  • except handles errors.
  • Multiple except blocks can handle different exceptions.
  • Exception as error provides the actual error message.
  • else executes when no exception occurs.
  • finally always executes.
  • Exception handling makes programs more reliable and user-friendly.