/

Python Exceptions: Handling Errors in Your Code

Python Exceptions: Handling Errors in Your Code

Handling errors is an important aspect of writing robust code, and Python provides us with exception handling to accomplish this. By using try-except blocks, we can handle errors that might occur during the execution of our code.

To use exception handling, we wrap the lines of code that might raise an error in a try: block. If an error occurs, Python will alert us, and we can specify how to handle that particular error using one or more except blocks.

Here’s an example:

1
2
3
4
5
6
try:
# some lines of code
except <ERROR1>:
# handler <ERROR1>
except <ERROR2>:
# handler <ERROR2>

You can catch all exceptions by using except without specifying an error type:

1
2
3
4
5
6
try:
# some lines of code
except <ERROR1>:
# handler <ERROR1>
except:
# catch all other exceptions

If no exceptions were raised, the code inside the else block will be executed:

1
2
3
4
5
6
7
8
try:
# some lines of code
except <ERROR1>:
# handler <ERROR1>
except <ERROR2>:
# handler <ERROR2>
else:
# no exceptions were raised, the code ran successfully

In addition to the try, except, and else blocks, you can use a finally block to perform an operation regardless of whether an error occurred or not:

1
2
3
4
5
6
7
8
9
10
try:
# some lines of code
except <ERROR1>:
# handler <ERROR1>
except <ERROR2>:
# handler <ERROR2>
else:
# no exceptions were raised, the code ran successfully
finally:
# do something in any case

The specific error that will occur depends on the operation being performed. For example, if you try to divide a number by zero, you will get a ZeroDivisionError. If you have a type conversion issue, you might get a TypeError.

Here’s an example:

1
2
result = 2 / 0
print(result)

This code will terminate with an error:

1
2
3
4
Traceback (most recent call last):
File "main.py", line 1, in <module>
result = 2 / 0
ZeroDivisionError: division by zero

By wrapping the problematic operation in a try: block, we can handle the error gracefully and continue with the program:

1
2
3
4
5
6
7
8
try:
result = 2 / 0
except ZeroDivisionError:
print('Cannot divide by zero!')
finally:
result = 1

print(result) # 1

You can also raise your own exceptions using the raise statement:

1
raise Exception('An error occurred!')

To handle this exception, you can use:

1
2
3
4
try:
raise Exception('An error occurred!')
except Exception as error:
print(error)

In addition to the built-in exceptions, you can define your own custom exception classes by extending the base Exception class:

1
2
class DogNotFoundException(Exception):
pass

Then, you can raise and handle your custom exceptions like this:

1
2
3
4
try:
raise DogNotFoundException()
except DogNotFoundException:
print('Dog not found!')

Tags: Python, exceptions, error handling, try-except blocks, raising exceptions, custom exceptions