0
0
Pythonprogramming~5 mins

Generic exception handling in Python

Choose your learning style9 modes available
Introduction

Generic exception handling helps your program catch any error that might happen, so it doesn't crash unexpectedly.

When you want to catch all possible errors without specifying each one.
When you are testing code and want to see if any error occurs.
When you want to show a friendly message instead of a program crash.
When you want to log errors for later review without stopping the program.
Syntax
Python
try:
    # code that might cause an error
except Exception:
    # code to run if any error happens

The try block contains code that might cause an error.

The except Exception block catches any error that is a subclass of Exception, which is most errors.

Examples
This catches the division by zero error and prints a message.
Python
try:
    x = 1 / 0
except Exception:
    print("Something went wrong")
This catches the error and shows what went wrong using the error message.
Python
try:
    print(undefined_variable)
except Exception as e:
    print(f"Error: {e}")
Sample Program

This program asks for a number and divides 10 by it. If the user enters zero or something not a number, it catches the error and shows a friendly message.

Python
try:
    number = int(input("Enter a number: "))
    result = 10 / number
    print(f"10 divided by {number} is {result}")
except Exception:
    print("Oops! Something went wrong.")
OutputSuccess
Important Notes

Using generic exception handling is helpful but can hide specific errors, so use it carefully.

You can get the error details by using except Exception as e and printing e.

Summary

Generic exception handling catches most errors to prevent crashes.

Use try and except Exception to handle errors simply.

Be careful not to hide important error details when using generic handling.