Python try and except

In the last lesson, we learned about Python Introduction to Exceptions. Now let’s catch errors with try and except so our program can respond safely.

Let’s Talk About Catching Errors

In the last article, we learned about exceptions. They are errors that happen while the program is running. And if nobody handles them, the program crashes.

Now let’s learn how to handle them. The main tool for this is the try and except block.

Think of it like this. We are walking on a path. There might be a hole. We do not know for sure. So we step carefully. If we fall, we are ready to catch ourselves.

try is like saying: “I am going to try this. It might work. It might not.”

except is like saying: “If it does not work, here is what I will do instead.”

The Basic Structure of try and except in Python

try:
# code that might raise an exception
except:
# code that runs if an exception happens

The code inside try is attempted. If an exception occurs, Python immediately jumps to the except block. It runs that code. Then the program continues after the try-except block.

If no exception occurs, the except block is skipped.

Let’s see a simple example.

try:
print(10 / 0)
except:
print("Something went wrong")

Output

Something went wrong

The division by zero raises a ZeroDivisionError. The except block catches it. And prints a message. The program does not crash.

Now if there is no error:

try:
print(10 / 2)
except:
print("Something went wrong")

Output

5.0

No exception. So the except block is skipped. The program prints the result.

Catching Specific Exceptions in Python

The bare except: catches everything. That is usually not a good idea. Because it can hide bugs. We might catch an exception we did not expect. And then we do not know what went wrong.

It is better to catch specific exceptions.

try:
number = int(input("Enter a number: "))
result = 100 / number
print(f"Result: {result}")
except ValueError:
print("That is not a valid number")
except ZeroDivisionError:
print("Cannot divide by zero")

Now if the user enters hello, it catches ValueError and prints “That is not a valid number”. If they enter 0, it catches ZeroDivisionError and prints “Cannot divide by zero”. If they enter a valid number, it prints the result.

That is much better. We handle each error appropriately.

Catching Multiple Exceptions in One Block

We can catch multiple exceptions in a single except block by putting them in a tuple.

try:
number = int(input("Enter a number: "))
result = 100 / number
print(f"Result: {result}")
except (ValueError, ZeroDivisionError):
print("Invalid input or division by zero")

This catches either ValueError or ZeroDivisionError. And prints the same message. That is useful when we want to handle them the same way.

Getting the Exception Object in Python

Sometimes we want to see the actual error message. We can capture the exception object using as.

try:
number = int(input("Enter a number: "))
result = 100 / number
print(f"Result: {result}")
except ValueError as e:
print(f"ValueError: {e}")
except ZeroDivisionError as e:
print(f"ZeroDivisionError: {e}")

If the user enters hello, the output is:

ValueError: invalid literal for int() with base 10: 'hello'

That gives more detail. It can be useful for logging or debugging.

The else Block in Python try and except

We can add an else block after the except blocks. It runs only if no exception occurred in the try block.

try:
number = int(input("Enter a number: "))
result = 100 / number
except ValueError:
print("That is not a valid number")
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print(f"Result: {result}")

If the user enters a valid number, the else block runs and prints the result. If an exception happens, the else block is skipped.

The else block is optional. But it can make our code clearer. It separates the code that should run only on success.

The finally Block (Brief Mention)

There is also a finally block. It runs no matter what. Whether an exception happened or not. We will cover it in a later article. But just so we know it exists.

try:
# some code
except:
# handle error
finally:
# always runs

Python try and except: A Real-Life Example

Let’s build a simple program that asks for two numbers and divides them.

try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
result = num1 / num2
except ValueError:
print("Please enter valid numbers")
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print(f"Result: {result}")

If the user enters 10 and 2, output is Result: 5.0.

If they enter 10 and 0, output is Cannot divide by zero.

If they enter abc, output is Please enter valid numbers.

That is clean and handles all the common errors.

Common Mistakes with Python try and except

Mistake 1: Using Bare except

try:
# some code
except:
pass

This catches everything and does nothing. It hides bugs. Let’s always catch specific exceptions.

Mistake 2: Putting Too Much Code in try

try:
# many lines of code
except:
print("Error")

If an error happens, we do not know which line caused it. Let’s keep the try block small. Only the code that might raise the exception.

Mistake 3: Catching an Exception We Cannot Handle

try:
# some code
except:
print("Something went wrong")

If we do not know how to handle an exception, it is better to let it crash. Or log it and re-raise. Let’s not just swallow it.

Mistake 4: Forgetting That except Can Have Multiple Blocks

try:
# some code
except ValueError:
print("Value error")
except ZeroDivisionError:
print("Zero division error")

That is correct. We can have as many except blocks as we need.

Mistake 5: Using else When We Do Not Need It

The else block is optional. Sometimes it is clearer to just put the success code after the try-except block. But if we want to be explicit, we use else.

A Real-Life Example with a Loop

Let’s ask the user for a number until they enter a valid one.

while True:
try:
number = int(input("Enter a number: "))
break
except ValueError:
print("That is not a valid number. Try again.")
print(f"You entered: {number}")

This keeps asking until the user enters a valid integer. The try block attempts to convert. If it fails, the except block prints a message and the loop continues. If it succeeds, break exits the loop.

That is a very common pattern.

Next, we will learn about Multiple Exceptions in Python and handle different errors in different ways.