- Python Try Except
- Exception Handling
- Example
- Example
- Many Exceptions
- Example
- Else
- Example
- Finally
- Example
- Example
- Raise an exception
- Example
- Example
- Python Print Exception – How to Try-Except-Print an Error
- What We’ll Cover
- What is an Exception?
- The try…except Syntax
- How to Handle Exceptions with try…except
- How to Print an Exception with try…except
- How to Print the Exception Name
- Conclusion
Python Try Except
The try block lets you test a block of code for errors.
The except block lets you handle the error.
The else block lets you execute code when there is no error.
The finally block lets you execute code, regardless of the result of the try- and except blocks.
Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and generate an error message.
These exceptions can be handled using the try statement:
Example
The try block will generate an exception, because x is not defined:
Since the try block raises an error, the except block will be executed.
Without the try block, the program will crash and raise an error:
Example
This statement will raise an error, because x is not defined:
Many Exceptions
You can define as many exception blocks as you want, e.g. if you want to execute a special block of code for a special kind of error:
Example
Print one message if the try block raises a NameError and another for other errors:
try:
print(x)
except NameError:
print(«Variable x is not defined»)
except:
print(«Something else went wrong»)
Else
You can use the else keyword to define a block of code to be executed if no errors were raised:
Example
In this example, the try block does not generate any error:
Finally
The finally block, if specified, will be executed regardless if the try block raises an error or not.
Example
This can be useful to close objects and clean up resources:
Example
Try to open and write to a file that is not writable:
try:
f = open(«demofile.txt»)
try:
f.write(«Lorum Ipsum»)
except:
print(«Something went wrong when writing to the file»)
finally:
f.close()
except:
print(«Something went wrong when opening the file»)
The program can continue, without leaving the file object open.
Raise an exception
As a Python developer you can choose to throw an exception if a condition occurs.
To throw (or raise) an exception, use the raise keyword.
Example
Raise an error and stop the program if x is lower than 0:
if x < 0:
raise Exception(«Sorry, no numbers below zero»)
The raise keyword is used to raise an exception.
You can define what kind of error to raise, and the text to print to the user.
Example
Raise a TypeError if x is not an integer:
if not type(x) is int:
raise TypeError(«Only integers are allowed»)
Python Print Exception – How to Try-Except-Print an Error
Kolade Chris
Every programming language has its way of handling exceptions and errors, and Python is no exception.
Python comes with a built-in try…except syntax with which you can handle errors and stop them from interrupting the running of your program.
In this article, you’ll learn how to use that try…except syntax to handle exceptions in your code so they don’t stop your program from running.
What We’ll Cover
What is an Exception?
In Python, an exception is an error object. It is an error that occurs during the execution of your program and stops it from running – subsequently displaying an error message.
When an exception occurs, Python creates an exception object which contains the type of the error and the line it affects.
Python has many built-in exceptions such as IndexError , NameError , TypeError , ValueError , ZeroDivisionError KeyError , and many more.
The try…except Syntax
Instead of allowing these exceptions to stop your program from running, you can put the code you want to run in a try block and handle the exception in the except block.
The basic syntax of try…except looks like this:
try: # code to run except: # handle error
How to Handle Exceptions with try…except
You can handle each of the exceptions mentioned in this article with try…except . In fact, you can handle all the exceptions in Python with try…except .
For example, if you have a large program and you don’t know whether an identifier exists or not, you can execute what you want to do with the identifier in a try block and handle a possible error in the except block:
try: print("Here's variable x:", x) except: print("An error occured") # An error occured
You can see that the except ran because there’s no variable called x in the code.
Keep reading. Because I will show you how to make those errors look better by showing you how to handle exceptions gracefully.
How to Print an Exception with try…except
But what if you want to print the exact exception that occurred? You can do this by assigning the Exception to a variable right in front of the except keyword.
When you do this and print the Exception to the terminal, it is the value of the Exception that you get.
This is how I printed the ZeroDivisionError exception to the terminal:
try: res = 190 / 0 except Exception as error: # handle the exception print("An exception occurred:", error) # An exception occurred: division by zero
And this is how I printed the NameError exception too:
try: print("Here's variable x:", x) except Exception as error: print("An error occurred:", error) # An error occurred: name 'x' is not defined
You can follow this pattern to print any exception to the terminal.
How to Print the Exception Name
What if you want to get the exact exception name and print it to the terminal? That’s possible too. All you need to do is use the type() function to get the type of the exception and then use the __name__ attribute to get the name of the exception.
This is how I modified the ZeroDivisionError example to print the exact exception:
try: res = 190 / 0 except Exception as error: # handle the exception print("An exception occurred:", type(error).__name__) # An exception occurred: ZeroDivisionError
And this is how I modified the other example to print the NameError example:
try: print("Here's variable x:", x) except Exception as error: print("An error occurred:", type(error).__name__) # An error occurred: NameError
Normally, when you encounter an Exception such as NameError and ZeroDivisionError , for example, you get the error in the terminal this way:
You can combine the type() function and that error variable to make the exception look better:
try: print("Here's variable x:", x) except Exception as error: print("An error occurred:", type(error).__name__, "–", error) # An error occurred: NameError – name 'x' is not defined
try: res = 190 / 0 except Exception as error: # handle the exception print("An exception occurred:", type(error).__name__, "–", error) # An exception occurred: ZeroDivisionError – division by zero
Conclusion
As shown in this article, the try…except syntax is a great way to handle errors and prevent your program from stopping during execution.
You can even print that Exception to the terminal by assigning the error to a variable, and get the exact type of the Exception with the type() function.