Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Raising and Handling Python Exceptions Show
Table of Contents
A Python program terminates as soon as it encounters an error. In Python, an error can be a syntax error or an exception. In this article, you will see what an exception is and how it differs from a syntax error. After that, you will learn about raising exceptions and making assertions. Then, you’ll finish with a demonstration of the try and except block. Exceptions versus Syntax ErrorsSyntax errors occur when the parser detects an incorrect statement. Observe the following example:
The arrow indicates where the parser ran into the syntax error. In this example, there was one bracket too many. Remove it and run your code again:
This time, you ran into an exception error. This type of error occurs whenever syntactically correct Python code results in an error. The last line of the message indicated what type of exception error you ran into. Instead of showing the message Raising an ExceptionWe can use If you
want to throw an error when a certain condition occurs using
When you run this code, the output will be the following:
The program comes to a halt and displays our exception to screen, offering clues about what went wrong. The AssertionError ExceptionInstead of waiting for a program to crash midway, you can also start by making an assertion in Python. We
Have a look at the following example, where it is asserted that the code will be executed on a Linux system:
If you run this code on a Linux machine, the assertion passes. If you were to run this code on a Windows machine, the outcome of the assertion would be
In this example, throwing an The try and except Block: Handling ExceptionsThe As you saw earlier,
when syntactically correct code runs into an error, Python will throw an exception error. This exception error will crash the program if it is unhandled. The The following function can help you understand the
The You
can give the function a
The way you handled the error here is by handing out a You got nothing. The good thing here is that the program did not crash. But it would be nice to see if some type of exception occurred whenever you ran your code. To this end, you can change the
Execute this code on a Windows machine:
When an exception occurs in a program running this function, the program will continue as well as inform you about the fact that the function call was not successful. What you did not get to see was the type of error that was thrown as a result of the function call. In order to see exactly what went wrong, you would need to catch the error that the function threw. The following code is an example where you capture
the
Running this function on a Windows machine outputs the following:
The first message is the In the previous example, you called a function that you wrote yourself. When you executed the function, you caught the Here’s another example where you open a file and use a built-in exception:
If file.log does not exist, this block of code will output the following: This is an informative message, and our program will still continue to run. In the Python docs, you can see that there are a lot of built-in exceptions that you can use here. One exception described on that page is the following:
To catch this type of exception and print it to screen, you could use the following code:
In this case, if file.log does not exist, the output will be the following:
You can have more than one function call in your Look at the following code. Here,
you first call the
If the file does not exist, running this code on a Windows machine will output the following:
Inside the
Here are the key takeaways:
The else ClauseIn Python, using the Look at the following example:
If you were to run this code on a Linux system, the output would be the following:
Because the program did not run into any exceptions, the You can also
If you were to execute this code on a Linux machine, you would get the following result:
From the output, you can see that the Cleaning Up After Using finallyImagine that you always had to implement some
sort of action to clean up after executing your code. Python enables you to do so using the Have a look at the following example:
In the previous code, everything in the
Summing UpAfter seeing the difference between syntax errors and exceptions, you learned about various ways to raise, catch, and handle exceptions in Python. In this article, you saw the following options:
Hopefully, this article helped you understand the basic tools that Python has to offer when dealing with exceptions. Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Raising and Handling Python Exceptions How do you return an exception in Python?To catch and print an exception that occurred in a code snippet, wrap it in an indented try block, followed by the command "except Exception as e" that catches the exception and saves its error message in string variable e . You can now print the error message with "print(e)" or use it for further processing. How do you raise a return in Python?You can't raise and return , but you could return multiple values, where the first is the same as what you're currently using, and the second indicates if an exception arose return True, sys. exc_info() == (None, None, None) or something similar but better suited to context. What does raise exception return?Raising an exception terminates the flow of your program, allowing the exception to bubble up the call stack. In the above example, this would let you explicitly handle TypeError later. If TypeError goes unhandled, code execution stops and you'll get an unhandled exception message. How do you manually raise an exception in Python?raise Exception("I know Python!") Replace Exception with the specific type of exception you want to throw.. Raise exception vs. raise exception (args) ... . Statement raise. The raise statement without any arguments re-raises the last exception. ... . Raise exception (args) from original_exception.. |