“except” Keyword in Python: Handling Exceptions in Your Code

"except" Keyword in Python: Handling Exceptions in Your Code

Handling exceptions is an important part of programming. When our Python code encounters an error, we need to be able to handle it in a way that prevents our program from crashing. Python has a built-in way to handle exceptions: the “except” keyword. In this article, we’ll explore how to use the “except” keyword to handle exceptions in your code.

What are Exceptions in Python?

In Python, an exception is an error that occurs during the execution of our program. This could be something like a syntax error, an out-of-bounds error, or a type error. When an exception occurs, our program will usually stop running and will display an error message.

For example, consider the following code:

a = 5
b = 0
print(a/b)

This code will result in a ZeroDivisionError. When Python tries to divide 5 by 0, it encounters an error and cannot continue. Instead, Python will display the following error message:

Traceback (most recent call last):
File "example.py", line 3, in 
    print(a/b)
ZeroDivisionError: division by zero

As we can see, the error message includes information about the type of error (ZeroDivisionError) and where the error occurred (line 3 of example.py). While this error message is helpful for debugging purposes, it isn’t very user-friendly. Instead of displaying an error message, we can use the except keyword to handle the exception in a more elegant way.

The Basic Syntax of ‘except’ Keyword in Python

The except keyword is used to handle exceptions in Python. The basic syntax for using except is as follows:

try:
    #some Python code
except SomeException:
    #handle the exception

Here’s what each component of the syntax means:

  • The try statement is used to enclose a block of code that might result in an exception.
  • The SomeException is the name of the exception that you want to handle.
  • The except statement is used to specify the code that should execute if an exception of type SomeException is encountered.

To illustrate this, let’s take a look at an example.

Example: Handling the ZeroDivisionError Exception

Let’s return to our previous example, where we tried to divide 5 by 0:

a = 5
b = 0
print(a/b)

As we saw earlier, this code raises a ZeroDivisionError exception. Instead of showing an error message, we can use the except keyword to gracefully handle the exception:

a = 5
b = 0
try:
    print(a/b)
except ZeroDivisionError:
    print("Oops! Cannot divide by zero.")

The code above contains a try statement that encloses the line that might raise an exception. If an exception occurs, Python jumps to the except statement, which handles the exception by printing a user-friendly error message. Here’s the output of this code:

Oops! Cannot divide by zero.

We can use the except keyword to handle any type of exception that we might encounter. For instance, let’s say that we want to handle the case where a user inputs a non-numeric value:

Example: Handling the ValueError Exception

Consider the following code, which prompts the user to enter a number:

num = input("Enter a number: ")
print(num * 5)

If the user inputs a non-numeric value, this code will raise a ValueError exception. Let’s use the except keyword to handle this exception:

num = input("Enter a number: ")
try:
    print(num * 5)
except ValueError:
    print("Oops! Invalid input.")

The code above contains a try statement that encloses the line that might raise an exception. If a ValueError exception occurs, Python jumps to the except statement, which handles the exception by printing a user-friendly error message:

Enter a number: abc
Oops! Invalid input.

Example: Handling Multiple Exceptions

It’s possible to handle multiple exceptions in a single try-except block. To do this, we simply add multiple except statements:

try:
    #some Python code
except SomeException:
    #handle the exception
except AnotherException:
    #handle another exception

For example, consider the following code:

x = 5
y = "abc"
try:
    print(x + y)
except TypeError:
    print("Oops! Unsupported operation.")
except ValueError:
    print("Oops! Invalid input.")

This code tries to add the integer 5 to the string "abc". This will result in a TypeError exception. If a TypeError exception occurs, Python jumps to the first except statement, which handles the exception gracefully by printing a user-friendly error message:

Oops! Unsupported operation.

If we change the value of y to a non-numeric value, then the code will raise a ValueError exception instead:

x = 5
y = "def"
try:
    print(x + y)
except TypeError:
    print("Oops! Unsupported operation.")
except ValueError:
    print("Oops! Invalid input.")

If a ValueError exception occurs, Python jumps to the second except statement, which handles the exception gracefully by printing a user-friendly error message:

Oops! Invalid input.

Example: Using the ‘finally’ Keyword

Sometimes we might want to perform some cleanup code after handling an exception. For example, if we have opened a file, we might want to close it even if an exception was raised. We can use the finally keyword to do this:

try:
    #some Python code
except SomeException:
    #handle the exception
finally:
    #cleanup code

The finally keyword is always executed, whether an exception was raised or not. In the example above, the finally statement contains code that should always be executed, such as closing a file:

try:
    f = open("file.txt")
    #some code
except Exception as e:
    print(e)
finally:
    f.close()

In the code above, we attempt to open a file called file.txt. If an exception occurs, such as a FileNotFoundError or an IOError, Python jumps to the except statement, which prints the error message. Then, the finally statement is executed, which closes the file in all cases.

Example: Creating Custom Exceptions

It’s possible to create custom exceptions in Python. Custom exceptions can be useful if you want to raise an error that’s specific to your program. To create a custom exception, define a new class that inherits from the Exception class:

class CustomException(Exception):
    def __init__(self, message):
        self.message = message

In this example, we define a custom exception called CustomException. Our custom exception takes one argument, which is the error message that we want to display when the exception is raised.

To raise our custom exception, we simply create an instance of the CustomException class and throw it:

raise CustomException("Oops! Custom exception.")

When our custom exception is raised, Python will display the error message that we specified:

CustomException: Oops! Custom exception.

Wrapping Up

The except keyword is a powerful way to handle exceptions in your Python code. With the except keyword, you can write code that gracefully handles errors and prevents your program from crashing. By using the try-except syntax, you can write code that anticipates errors and provides a user-friendly way to handle them. Custom exceptions give you even more flexibility in how you handle errors, allowing you to define error messages that are specific to your program.

Leave a Reply

Your email address will not be published. Required fields are marked *