Python FunctionsPython Functions1

Python Exception HandlingPython Exception Handling1

Python Exception Handling



Sometimes, when your program runs, things can go wrong — like dividing a number by zero, or trying to open a file that doesn’t exist. These problems are called exceptions in Python.

What is an Exception?

An exception is a message that Python shows when something goes wrong while running your code. It stops the program unless you tell Python how to handle it.

Why Do Exceptions Exist?

Exceptions are helpful! They don’t crash your computer — they just let you know something unusual happened. If you don’t handle them, your program will stop. But if you do, your program can keep going or show a friendly message instead.

Example: A Simple Error

print(10 / 0)

Output:

ZeroDivisionError: division by zero

Why this happened: You’re trying to divide 10 by 0, which is not allowed in math. So Python shows a ZeroDivisionError.

How to Handle Exceptions

Python gives us a way to handle such situations using try and except blocks.

Example: Handling Division by Zero

try:
    print(10 / 0)
except ZeroDivisionError:
    print("Oops! You can't divide by zero.")
    

Output:

Oops! You can't divide by zero.

Why this works: The code inside try might cause an error. If it does, the code inside except runs instead of crashing the program.

Another Example: Converting Text to a Number

try:
    number = int("hello")
except ValueError:
    print("That’s not a number!")
    

Output:

That’s not a number!

Why: You’re trying to turn the word "hello" into a number. That’s not possible, so Python gives a ValueError.

Using a General Except

try:
    print(10 / 0)
except:
    print("Some error happened!")
    

Note: You can use except alone, but it's better to catch specific errors like ZeroDivisionError or ValueError if you know what to expect.

Common Exception Types

Conclusion

Exceptions are normal in programming. They help you find and fix problems. Using try and except, you can write programs that don’t crash — even when something goes wrong.

Next, we’ll learn how to handle different types of input from users and avoid common mistakes!



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M