Python Try Except
- Previous Page Python PIP
- Next Page Python Command Input
try
block allows you to test code blocks to find errors.
except
block allows you to handle errors.
finally
block allows you to execute code regardless of the result of the try and except blocks.
Exception handling
When we call Python and an error or exception occurs, we usually stop and generate an error message.
You can use try
statement handles these exceptions:
Example
The try block will generate an exception because x is undefined:
try: print(x) except: print("An exception occurred")
Because the try block raised an error, the except block will be executed.
If there is no try block, the program will crash and raise an error:
Example
This statement will raise an error because x is undefined:
print(x)
Multiple exceptions
You can define any number of exception blocks as needed, for example, if you want to execute special code blocks for special types of errors:
Example
If the try block raises NameError
Print a message if it is another error:
try: print(x) except NameError: print("Variable x is not defined") except: print("Something else went wrong")
Else
If no error is raised, you can use else
keywords to define the code block to be executed:
Example
In this example,try
The block will not generate any errors:
try: print("Hello") except: print("Something went wrong") else: print("Nothing went wrong")
Finally
If specified finally
Whether the try block raises an error or not, the finally block will always be executed.
Example
try: print(x) except: print("Something went wrong") finally: print("The 'try except' is finished")
This is very useful for closing objects and cleaning up resources:
Example
Attempt to open and write to an unwritable file:
try: f = open("demofile.txt") f.write("Lorum Ipsum") except: print("Something went wrong when writing to the file") finally: f.close()
The program can continue, and the file object will not be opened.
Raising Exceptions
As a Python developer, you can choose to raise an exception when a condition occurs.
To raise (trigger) an exception, use raise
Keywords.
Example
If x is less than 0, an exception is raised and the program is terminated:
x = -1 if x < 0: raise Exception("Sorry, no numbers below zero")
raise
Keywords are used to raise exceptions.
You can define the type of exception raised and the text printed to the user.
Example
If x is not an integer, a TypeError is raised:
x = "hello" if not type(x) is int: raise TypeError("Only integers are allowed")
- Previous Page Python PIP
- Next Page Python Command Input