Python Exceptions Information
A Python program ends when it experiences a mistake. In Python, a mistake can be a grammar blunder or a special case. In this article, you will perceive what an exemption is and how it varies from a punctuation mistake. From that point forward, you will find out about raising special cases and making declarations. At that point, you’ll complete with an exhibition of the attempt and aside from square.
Free PDF Download: Python 3 Cheat Sheet
Exceptions versus Syntax Errors
Syntax errors occur when the parser detects an incorrect statement. Observe the following example:
1 | <span class="x">>>> print( 0 / 0 ))</span> File <span class="nb">"<stdin>"</span>, line <span class="m">1</span> <span class="k">print</span><span class="p">(</span> <span class="mi">0</span> <span class="o">/</span> <span class="mi">0</span> <span class="p">))</span> <span class="o">^</span> <span class="gr">SyntaxError</span>: <span class="n">invalid syntax</span> |
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:
1 | <span class="x">>>> print( 0 / 0)</span> <span class="gt">Traceback (most recent call last):</span> File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span> <span class="gr">ZeroDivisionError</span>: <span class="n">integer division or modulo by zero</span> |
This time, you kept running into a special case mistake. This kind of mistake happens at whatever point grammatically adjust Python code brings about a blunder. The last line of the message showed what sort of special case mistake you kept running into.
Instead of showing the message exception error
, Python details what type of exception error was encountered. In this case, it was a ZeroDivisionError
. Python comes with various built-in exceptions as well as the possibility to create self-defined exceptions.
Raising an Exception
We can use raise
to throw an exception if a condition occurs. The statement can be complemented with a custom exception.
If you want to throw an error when a certain condition occurs using raise
, you could go about it like this:
1 | <span class="n">x</span> <span class="o">=</span> <span class="mi">10</span> <span class="k">if</span> <span class="n">x</span> <span class="o">></span> <span class="mi">5</span><span class="p">:</span> <span class="k">raise</span> <span class="ne">Exception</span><span class="p">(</span><span class="s1">'x should not exceed 5. The value of x was: {}'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">x</span><span class="p">))</span> |
When you run this code, the output will be the following:
1 | <span class="gt">Traceback (most recent call last):</span> File <span class="nb">"<input>"</span>, line <span class="m">4</span>, in <span class="n"><module></span> <span class="gr">Exception</span>: <span class="n">x should not exceed 5. The value of x was: 10</span> |
The program comes to a halt and displays our exception to screen, offering clues about what went wrong.
The AssertionError
Exception
Instead of waiting for a program to crash midway, you can also start by making an assertion in Python. We assert
that a certain condition is met. If this condition turns out to be True
, then that is excellent! The program can continue. If the condition turns out to be False
, you can have the program throw an AssertionError
exception.
Have a look at the following example, where it is asserted that the code will be executed on a Linux system:
1 | <span class="kn">import</span> <span class="nn">sys</span> <span class="k">assert</span> <span class="p">(</span><span class="s1">'linux'</span> <span class="ow">in</span> <span class="n">sys</span><span class="o">.</span><span class="n">platform</span><span class="p">),</span> <span class="s2">"This code runs on Linux only."</span> |
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 False
and the result would be the following:
1 | <span class="gt">Traceback (most recent call last):</span> File <span class="nb">"<input>"</span>, line <span class="m">2</span>, in <span class="n"><module></span> <span class="gr">AssertionError</span>: <span class="n">This code runs on Linux only.</span> |
In this example, throwing an AssertionError
exception is the last thing that the program will do. The program will come to halt and will not continue. What if that is not what you want?
The try
and except
Block: Handling Exceptions
The try
and except
block in Python is used to catch and handle exceptions. Python executes code following the try
statement as a “normal” part of the program. The code that follows the except
statement is the program’s response to any exceptions in the preceding try
clause.
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 except
clause determines how your program responds to exceptions.
The following function can help you understand the try
and except
block:
1 | <span class="k">def</span> <span class="nf">linux_interaction</span><span class="p">():</span> <span class="k">assert</span> <span class="p">(</span><span class="s1">'linux'</span> <span class="ow">in</span> <span class="n">sys</span><span class="o">.</span><span class="n">platform</span><span class="p">),</span> <span class="s2">"Function can only run on Linux systems."</span> <span class="k">print</span><span class="p">(</span><span class="s1">'Doing something.'</span><span class="p">)</span> |
The linux_interaction()
can only run on a Linux system. The assert
in this function will throw an AssertionError
exception if you call it on an operating system other then Linux.
You can give the function a try
using the following code:
1 | <span class="k">try</span><span class="p">:</span> <span class="n">linux_interaction</span><span class="p">()</span> <span class="k">except</span><span class="p">:</span> <span class="k">pass</span> |
The way you handled the error here is by handing out a pass
. If you were to run this code on a Windows machine, you would get the following output:
1 |
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 pass
into something that would generate an informative message, like so:
1 | <span class="k">try</span><span class="p">:</span> <span class="n">linux_interaction</span><span class="p">()</span> <span class="k">except</span><span class="p">:</span> <span class="k">print</span><span class="p">(</span><span class="s1">'Linux function was not executed'</span><span class="p">)</span> |
Execute this code on a Windows machine:
1 | <span class="go">Linux function was not executed</span> |
At the point when a special case happens in a program running this capacity, the program will proceed and additionally advise you about the way that the capacity call was not fruitful.
What you didn’t get the opportunity to see was the sort of blunder that was tossed because of the capacity call. With a specific end goal to see precisely what turned out badly, you would need to get the mistake that the capacity tossed.
The following code is an example where you capture the AssertionError
and output that message to screen:
1 | <span class="k">try</span><span class="p">:</span> <span class="n">linux_interaction</span><span class="p">()</span> <span class="k">except</span> <span class="ne">AssertionError</span> <span class="k">as</span> <span class="n">error</span><span class="p">:</span> <span class="k">print</span><span class="p">(</span><span class="n">error</span><span class="p">)</span> <span class="k">print</span><span class="p">(</span><span class="s1">'The linux_interaction() function was not executed'</span><span class="p">)</span> |
Running this function on a Windows machine outputs the following:
1 | <span class="go">Function can only run on Linux systems.</span> <span class="go">The linux_interaction() function was not executed</span> |
The first message is the AssertionError
, informing you that the function can only be executed on a Linux machine. The second message tells you which function was not executed.
In the previous example, you called a function that you wrote yourself. When you executed the function, you caught the AssertionError
exception and printed it to screen.
Here’s another example where you open a file and use a built-in exception:
1 | <span class="k">try</span><span class="p">:</span> <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'file.log'</span><span class="p">)</span> <span class="k">as</span> <span class="nb">file</span><span class="p">:</span> <span class="n">read_data</span> <span class="o">=</span> <span class="nb">file</span><span class="o">.</span><span class="n">read</span><span class="p">()</span> <span class="k">except</span><span class="p">:</span> <span class="k">print</span><span class="p">(</span><span class="s1">'Could not open file.log'</span><span class="p">)</span> |
If file.log does not exist, this block of code will output the following:
1 | <span class="go">Could not open file.log</span> |
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:
Exception
FileNotFoundError
Raised when a file or directory is requested but doesn’t exist. Corresponds to errno ENOENT.
To catch this type of exception and print it to screen, you could use the following code:
1 | <span class="k">try</span><span class="p">:</span> <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'file.log'</span><span class="p">)</span> <span class="k">as</span> <span class="nb">file</span><span class="p">:</span> <span class="n">read_data</span> <span class="o">=</span> <span class="nb">file</span><span class="o">.</span><span class="n">read</span><span class="p">()</span> <span class="k">except</span> <span class="n">FileNotFoundError</span> <span class="k">as</span> <span class="n">fnf_error</span><span class="p">:</span> <span class="k">print</span><span class="p">(</span><span class="n">fnf_error</span><span class="p">)</span> |
In this case, if file.log does not exist, the output will be the following:
1 | <span class="go">[Errno 2] No such file or directory: 'file.log'</span> |
You can have more than one function call in your try
clause and anticipate catching various exceptions. A thing to note here is that the code in the try
clause will stop as soon as an exception is encountered.
Warning: Catching Exception
hides all errors…even those which are completely unexpected. This is why you should avoid bare except
clauses in your Python programs. Instead, you’ll want to refer to specific exception classes you want to catch and handle. You can learn more about why this is a good idea in this tutorial.
Look at the following code. Here, you first call the linux_interaction()
function and then try to open a file:
1 | <span class="k">try</span><span class="p">:</span> <span class="n">linux_interaction</span><span class="p">()</span> <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'file.log'</span><span class="p">)</span> <span class="k">as</span> <span class="nb">file</span><span class="p">:</span> <span class="n">read_data</span> <span class="o">=</span> <span class="nb">file</span><span class="o">.</span><span class="n">read</span><span class="p">()</span> <span class="k">except</span> <span class="n">FileNotFoundError</span> <span class="k">as</span> <span class="n">fnf_error</span><span class="p">:</span> <span class="k">print</span><span class="p">(</span><span class="n">fnf_error</span><span class="p">)</span> <span class="k">except</span> <span class="ne">AssertionError</span> <span class="k">as</span> <span class="n">error</span><span class="p">:</span> <span class="k">print</span><span class="p">(</span><span class="n">error</span><span class="p">)</span> <span class="k">print</span><span class="p">(</span><span class="s1">'Linux linux_interaction() function was not executed'</span><span class="p">)</span> |
If the file does not exist, running this code on a Windows machine will output the following:
1 | <span class="go">Function can only run on Linux systems.</span> <span class="go">Linux linux_interaction() function was not executed</span> |
Inside the try
clause, you ran into an exception immediately and did not get to the part where you attempt to open file.log. Now look at what happens when you run the code on a Linux machine:
1 | <span class="go">[Errno 2] No such file or directory: 'file.log'</span> |
Here are the key takeaways:
- A
try
clause is executed up until the point where the first exception is encountered. - Inside the
except
clause, or the exception handler, you determine how the program responds to the exception. - You can anticipate multiple exceptions and differentiate how the program should respond to them.
- Avoid using bare
except
clauses.
The else
Clause
In Python, using the else
statement, you can instruct a program to execute a certain block of code only in the absence of exceptions.
Look at the following example:
1 | <span class="k">try</span><span class="p">:</span> <span class="n">linux_interaction</span><span class="p">()</span> <span class="k">except</span> <span class="ne">AssertionError</span> <span class="k">as</span> <span class="n">error</span><span class="p">:</span> <span class="k">print</span><span class="p">(</span><span class="n">error</span><span class="p">)</span> <span class="k">else</span><span class="p">:</span> <span class="k">print</span><span class="p">(</span><span class="s1">'Executing the else clause.'</span><span class="p">)</span> |
If you were to run this code on a Linux system, the output would be the following:
1 | <span class="go">Doing something.</span> <span class="go">Executing the else clause.</span> |
Because the program did not run into any exceptions, the else
clause was executed.
You can also try
to run code inside the else
clause and catch possible exceptions there as well:
1 | <span class="k">try</span><span class="p">:</span> <span class="n">linux_interaction</span><span class="p">()</span> <span class="k">except</span> <span class="ne">AssertionError</span> <span class="k">as</span> <span class="n">error</span><span class="p">:</span> <span class="k">print</span><span class="p">(</span><span class="n">error</span><span class="p">)</span> <span class="k">else</span><span class="p">:</span> <span class="k">try</span><span class="p">:</span> <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'file.log'</span><span class="p">)</span> <span class="k">as</span> <span class="nb">file</span><span class="p">:</span> <span class="n">read_data</span> <span class="o">=</span> <span class="nb">file</span><span class="o">.</span><span class="n">read</span><span class="p">()</span> <span class="k">except</span> <span class="n">FileNotFoundError</span> <span class="k">as</span> <span class="n">fnf_error</span><span class="p">:</span> <span class="k">print</span><span class="p">(</span><span class="n">fnf_error</span><span class="p">)</span> |
If you were to execute this code on a Linux machine, you would get the following result:
1 | <span class="go">Doing something.</span> <span class="go">[Errno 2] No such file or directory: 'file.log'</span> |
From the output, you can see that the linux_interaction()
function ran. Because no exceptions were encountered, an attempt to open file.log was made. That file did not exist, and instead of opening the file, you caught the FileNotFoundError
exception.
Tidying Up After Using finally
Imagine 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 finally
clause.
Have a look at the following example:
1 | <span class="k">try</span><span class="p">:</span> <span class="n">linux_interaction</span><span class="p">()</span> <span class="k">except</span> <span class="ne">AssertionError</span> <span class="k">as</span> <span class="n">error</span><span class="p">:</span> <span class="k">print</span><span class="p">(</span><span class="n">error</span><span class="p">)</span> <span class="k">else</span><span class="p">:</span> <span class="k">try</span><span class="p">:</span> <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'file.log'</span><span class="p">)</span> <span class="k">as</span> <span class="nb">file</span><span class="p">:</span> <span class="n">read_data</span> <span class="o">=</span> <span class="nb">file</span><span class="o">.</span><span class="n">read</span><span class="p">()</span> <span class="k">except</span> <span class="n">FileNotFoundError</span> <span class="k">as</span> <span class="n">fnf_error</span><span class="p">:</span> <span class="k">print</span><span class="p">(</span><span class="n">fnf_error</span><span class="p">)</span> <span class="k">finally</span><span class="p">:</span> <span class="k">print</span><span class="p">(</span><span class="s1">'Cleaning up, irrespective of any exceptions.'</span><span class="p">)</span> |
In the previous code, everything in the finally
clause will be executed. It does not matter if you encounter an exception somewhere in the try
or else
clauses. Running the previous code on a Windows machine would output the following:
1 | <span class="go">Function can only run on Linux systems.</span> <span class="go">Cleaning up, irrespective of any exceptions.</span> |
Summing Up
After 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:
raise
allows you to throw an exception at any time.assert
enables you to verify if a certain condition is met and throw an exception if it isn’t.- In the
try
clause, all statements are executed until an exception is encountered. except
is used to catch and handle the exception(s) that are encountered in the try clause.else
lets you code sections that should run only when no exceptions are encountered in the try clause.finally
enables you to execute sections of code that should always run, with or without any previously encountered exceptions.
Free PDF Download: Python 3 Cheat Sheet
Hopefully, this article helped you understand the basic tools that Python has to offer when dealing with exceptions.
[ Improve Your Python With ???? Python Tricks ???? — Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]