Python Try Except: Step-By-Step Examples

by | Python

As a programmer, you may encounter situations where your code could run into errors or exceptions, so it’s crucial to understand how to handle different types of errors in your code. Handling errors is a crucial part of the coding cycle. One common way to handle errors in Python is by using the try-except technique.

The Python try-except technique consists of a try block and an except block. The try block contains the code that might generate an error or exception, and the except block holds the code to handle those errors or exceptions.

Python Try Except

When your code runs without any issue within the try block, the except block is bypassed. However, if an error or exception occurs within the try block, the code you’ve written in the except block will execute to address the issue.

In this article, we will discuss Python’s try-expect block, the different types of errors and exceptions you may encounter when writing code, and how you can handle them with the try-except statements.

Let’s get into it!

What are the Types of Errors in Python?

In Python, errors can be roughly classified into two main types:

1. Syntax Errors: These are also known as parsing errors caused by incorrect grammar in the code. Syntax errors are detected by the Python interpreter and halt the execution of your program.

The following is an example of a syntax error in Python:

print("Hello, world!"

In this example, the closing parenthesis is missing, so Python does not understand this instruction, and therefore it’s a syntax error.

Example of a Syntax Error in Python

Exceptions: Exceptions occur when something goes wrong during the execution of a program, even if the code is syntactically correct. These can include logical errors or runtime errors such as invalid inputs or division by zero.

The following function is an example of an exception in Python:

print(5 / 0)

This line of code will cause a ZeroDivisionError exception, which happens when you try to divide a number by zero.

Example of Exception in Python

In the image above, you can see that an exception occurred when we divided 5 by 0.

Now that you have an understanding of what exceptions exist in Python, we’ll see how we can handle exceptions with a Try-Except statement in Python. Let’s take a look at the syntax of Try and Except blocks in Python in the next section.

What is the Syntax of Try and Except Block?

The syntax of a function defines how you should use that function in your code, including what arguments it takes and what it returns.

We have listed the syntax of the try clause and except blocks, along with the else clause and finally blocks below.

1. Syntax of Try Statement

The try statement allows you to test a block of code for errors. When you write code within the try block, Python will execute it as a normal part of your program.

To use a try statement, simply enclose your code within the try block:

    # Your code here

2. Syntax of Except Clause

The except clause handles the errors that might occur during the execution of the try block. You can specify the type of exception you want to catch or use a general except statement to handle all exceptions.

The following syntax shows a specific exception type:

    # Your code here
except ValueError:
    # Handle ValueError exception

To handle exception classes in general or multiple exceptions, you can use the syntax given below:

    # Your code here
except Exception:
    # Handle any exception

3. Syntax of Else Clause/Block

The else clause allows you to execute the code block when there are no errors in the try block.

To use an else clause, you can place it after the except block as shown below:

    # Your code here
except ValueError:
    # Handle ValueError exception
    # Code to execute when there are no errors

4. Syntax of Finally Block

The finally block lets you execute code, regardless of the result of the try and except blocks. This can be useful for actions that you want to perform whether or not an exception was raised.

To use the finally block, you can place it after the else block:

    # Your code here
except ValueError:
    # Handle ValueError exception
    # Code to execute when there are no errors
    # Code to execute regardless of the result of the try and except blocks

To see the above syntax in action, we’ll look at an example of handling exceptions with the try-except block in Python.

Handling Exceptions With Try-Except in Python

When an error occurs, Python will normally stop and generate an error message. You can handle multiple exceptions by using a try and except block.

In the example below, we handle the division by zero error previously generated when we divided 5 by 0.

    print(5 / 0)
except ZeroDivisionError:
    print("You can't divide by zero!")

In this code, an exception occurs but the program will continue to run and print out “You can’t divide by zero!” instead of stopping with an error.

Handling Zero Division Error with Try Except

Using try and except blocks allows you to control the flow of your program. By handling specific exceptions, you can provide helpful feedback to the user and keep your program running when an error pops up.

In the example above, you can see that we used the ZeroDivisionError built-in exception to handle the case. Similar to this, there are other types of built-in exceptions as well.

Familiarity with these exception types will help you decide which expectation to use when you encounter an error in your Python code, so let’s take a look at some exceptions in the next section.

What are the Types of Built-In Exceptions?

In Python, exceptions are instances of a class derived from the BaseException class. When errors are detected, Python raises an exception. There are several built-in exceptions that you’re likely to encounter while you write programs in Python.

Let’s have a look at some of the most common ones:

  1. ZeroDivisionError: This occurs when you try to divide a number by zero.

  2. NameError: This is raised when you try to use a variable or function that hasn’t been defined.

  3. ValueError: Happens when you pass an argument of the correct type but with an invalid value.

  4. TypeError: This one occurs when you pass an argument of the wrong data type.

  5. FileNotFoundError: Happens when you try to open or access a file that does not exist.

  6. ImportError: Raised when you try to import a module or package that doesn’t exist or can’t be found.

Other relevant exceptions include:

  1. OverflowError: This error is raised when a calculation result is too large to be represented.

  2. FloatingPointError: This one is raised when a floating point operation fails.

  3. IndexError: Happens when you try to access an index that is out of the range of a sequence (e.g., list or tuple).

  4. KeyError: Occurs when you try to access a key that does not exist in a dictionary.

  5. EOFError: Raised when Python encounters the End Of File (EOF) while reading input, usually from a read() call.

  6. ArithmeticError: A superclass for arithmetic exceptions, such as ZeroDivisionError, OverflowError, and FloatingPointError.

Sometimes, it might be necessary to use user-defined exceptions such as pass statement in a block where an exception is expected. This should be done judiciously as it might suppress other exceptions.

We have provided you with the above list of common exceptions errors so that you can use it as a guide for handling possible exceptions when writing your Python programs.

Please note that most exceptions can be caught and handled, but care should be taken to handle the most recent call to avoid nested handling of other exception cases.

In the next section, we will look at some use cases of the try-except block in Python. Let’s get into it!

5 Use Cases of Try-Except Block

Try Except block is one of the widely used techniques for handling errors. Following are some of the use cases of the Try Except block in Python:

1. File Handling with Try Except

When working with files, there’s always a chance that the file doesn’t exist or isn’t in the location your script is trying to access it from.

The following code will raise exception when we try opening a file that is not present.

    with open('file.txt', 'r') as file:
except FileNotFoundError:
    print('Sorry, this file does not exist.')

In this code, we are trying to open and read a file called ‘file.txt’. If ‘file.txt’ doesn’t exist, an exception occurs but instead of an error stopping your program, it will print ‘Sorry, this file does not exist.’

Using Try and Except to handle file handling errors

2. Handling User Input with Try Except

User input is another area where exceptions often occur. Users may provide data in an unexpected format, or give an input that’s outside the acceptable range.

The following example shows how to handle user input with a try-except block:

    age = int(input("Enter your age: "))
except ValueError:
    print("That's not a valid age. Please enter a number.")

In this code, we are asking the user to input their age. If they input something that can’t be converted to an integer (like a word or a letter), an exception occurs but instead of the program crashing, it will print ‘That’s not a valid age. Please enter a number.’

Handling User Input with Try Except

3. Accessing Non-Existent Dictionary Keys

In Python, a dictionary is a mutable, unordered collection of key-value pairs, where each key must be unique.

When you try to access a key that doesn’t exist in a dictionary, Python raises a KeyError. You can use try and except to handle this exception as shown in the example below:

dictionary = {"key1": "value1", "key2": "value2"}

except KeyError:
    print("The key does not exist in the dictionary.")

In this code, you’re trying to print the value for ‘key3’ from a dictionary. If ‘key3’ does not exist in the dictionary, an exception occurs but instead of the program stopping with an error, it will print ‘The key does not exist in the dictionary.’

Accessing Non-Existent Dictionary Keys

4. Converting a String to an Integer

There may be times when you want to convert a string to an integer. But if the string doesn’t represent a valid integer, Python will raise a ValueError.

You can use try and except to handle this case:

    num = int("hello")
except ValueError:
    print("That string can't be converted to integer.")

In this case, ‘hello’ can’t be converted to an integer, so Python raises a ValueError and prints ‘That string can’t be converted to integer.’

Handling errors when converting a string to an integer

5. Importing a Module

When importing a module in Python, it’s possible that the module doesn’t exist or isn’t installed. Python will raise an ImportError in such cases.

To handle this case, you can use the following code:

    import some_module
except ImportError:
    print("The module 'some_module' is not installed.")

In the above example, if ‘some_module’ isn’t installed or doesn’t exist, Python will raise an ImportError and print ‘The module ‘some_module’ is not installed.’

Handling errors when importing a module

To learn more about writing code in Python and handling expectations, check the following video out:

Next, we will look at some of the best practices for handling exceptions. Let’s dive into it!

Exception Handling Best Practices

In this section, we have listed some of the best practices for handling exceptions with Try Except block. Some best practices for handling exceptions are:

1. Be Specific with Exceptions

When you’re writing your code, catching exceptions as specifically as possible is crucial. This means that instead of just catching a general exception name, you should catch the actual type of exception that you expect.

This way, you’ll know exactly what kind of error occurred, and you’ll be able to handle it appropriately.

2. Don’t Suppress Exceptions

When you’re dealing with exceptions, you might be tempted to just catch it with an exception handler and not do anything with it. This is generally a bad idea.

If an error happens, it’s usually because there’s something that needs to be fixed. If you suppress the exception class, the error could go unnoticed and cause problems later on.

3. Use Finally for Cleanup Code

Sometimes, you have some code that you need to run regardless of whether an error happened or not. This could be something like closing a file or releasing some resources.

In these cases, you can use a finally block. The code inside the finally block will run no matter what, so it’s a great place to put your cleanup code.

    # Some code here
    # This code will run no matter what

4. Raise Exceptions When Necessary

There might be situations where you need to let the user of your code know that something went wrong.

In these cases, you can raise an exception. This will immediately stop the execution of your code and inform the user that an error occurred.

if not valid_input:
    raise ValueError("Your input was not valid!")

Understanding and implementing these best practices will make your code more robust, easier to debug, and prevent unexpected crashes.

Final Thoughts

To wrap it up, knowing how to use try and except in Python really helps when you’re writing your code and encountering exceptions in it.

They let your program deal with errors smoothly, instead of just stopping suddenly. It’s a way of making sure your code can handle surprises and keep going.

Plus, when you use try and except, it shows you’re really thinking about what could go wrong and getting ready for it. So take the time to learn these tools — they’re super useful when you’re writing code in Python!

author avatar
Sam McKay, CFA
Sam is Enterprise DNA's CEO & Founder. He helps individuals and organizations develop data driven cultures and create enterprise value by delivering business intelligence training and education.

Related Posts