- Python Try Except
- Exception Handling
- Example
- Example
- Many Exceptions
- Example
- Else
- Example
- Finally
- Example
- Example
- Raise an exception
- Example
- Example
- Python Try-Except for Exception Handling
- Try except is a fundamental concept in Python, and it is essential for beginners to understand. By using try except, you can prevent your programs from crashing and ensure that they continue to run even if an error occurs.
- How to use try-except, try-except-else?
- Catch multiple exceptions in one except block
- Handling multiple exceptions with one except block
- Re-raising exceptions in Python
- When to use the else clause
- Make use of [finally clause]
- Use the As keyword to catch specific exception types
- Best practice for manually raising exceptions
- How to skip through errors and continue execution
- Most common exception errors
- Examples of most common exceptions
- Summary – How to Best Use Try-Except in Python
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 Try-Except for Exception Handling
Try except is a fundamental concept in Python, and it is essential for beginners to understand. By using try except, you can prevent your programs from crashing and ensure that they continue to run even if an error occurs.
In Python programming, exception handling allows a programmer to enable flow control. And it has no. of built-in exceptions to catch errors in case your code breaks. Using try-except is the most common and natural way of handling unexpected errors along with many more exception-handling constructs. In this tutorial, you’ll get to explore some of the best techniques to use try-except in Python.
How to use try-except, try-except-else?
Error Handling or Exception Handling in Python can be enforced by setting up exceptions. Using a try block, you can implement an exception and handle the error inside an except block. Whenever the code breaks inside a try block, the regular code flow will stop and the control will get switched to the except block for handling the error.
Why use Try-Except/Try-Except-else Clause? With the help of try-except and try-except-else, you can avoid many unknown problems that could arise from your code. For example, the Python code using LBYL (Look before you leap) style can lead to race conditions. Here, the try-except clause can come to rescue you. Also, there are cases where your code depends critically on some information that could get outdated by the time you receive it. For example, the code making calls to os.path.exists or Queue. full may fail as these functions might return data that become stale by the time you use it. The wiser choice here would be to follow the try-except-else style in your code to manage the above cases more reliably.
Raising exceptions is also permissible in Python. It means you can throw or raise an exception whenever it is needed. You can do it simply by calling [raise Exception(‘Test error!’)] from your code. Once raised, the exception will stop the current execution as usual and will go further up in the call stack until handled.
Why use Exceptions? They not only help solve popular problems like race conditions but are also very useful in controlling errors in areas like loops, file handling, database communication, network access, and so on.
Sometimes, you may need a way to allow any arbitrary exception and also want to be able to display the error or exception message.
It is easily achievable using the Python exceptions. Check the below code. While testing, you can place the code inside the try block in the below example.
try: #your code except Exception as ex: print(ex)
Catch multiple exceptions in one except block
You can catch multiple exceptions in a single except block. See the below example.
Please note that you can separate the exceptions from the variable with a comma which is applicable in Python 2.6/2.7. But you can’t do it in Python 3. So, you should prefer to use the [as] keyword.
Handling multiple exceptions with one except block
There are many ways to handle multiple exceptions. The first of them requires placing all the exceptions which are likely to occur in the form of a tuple. Please see below.
try: file = open('input-file', 'open mode') except (IOError, EOFError) as e: print("Testing multiple exceptions. <>".format(e.args[-1]))
The next method is to handle each exception in a dedicated except block. You can add as many except blocks as needed. See the below example.
try: file = open(‘input-file’, ‘open mode’) except EOFError as ex: print(«Caught the EOF error.») raise ex except IOError as e: print(«Caught the I/O error.») raise ex
Last but not least is to use the except without mentioning any exception attribute.
try: file = open('input-file', 'open mode') except: # In case of any unhandled error, throw it away raise
This method can be useful if you don’t have any clue about the exception possibly thrown by your program.
Re-raising exceptions in Python
Exceptions once raised keep moving up in the call stack. Though you can add an except clause which could just have a “raise” call without any argument. It’ll result in reraising the exception.
try: # Intentionally raise an exception. raise Exception('I learn Python!') except: print("Entered in except.") # Re-raise the exception. raise
Entered in except. Traceback (most recent call last): File «python», line 3, in
When to use the else clause
Use an else clause right after the try-except block. The else clause will get hit only if no exception is thrown. The else statement should always precede the except blocks.
In else blocks, you can add code that you wish to run when no errors occurred.
See the below example. In this sample, you can see a while loop running infinitely. The code is asking for user input and then parses it using the built-in [int()] function. If the user enters a zero value, then the except block will get hit. Otherwise, the code will flow through the else block.
while True: # Enter integer value from the console. x = int(input()) # Divide 1 by x to test error cases try: result = 1 / x except: print("Error case") exit(0) else: print("Pass case") exit(1)
Make use of [finally clause]
If you have a code that you want to run in all situations, then write it inside the [finally block]. Python will always run the instructions coded in the [finally block]. It is the most common way of doing clean-up tasks. You can also make sure the clean-up gets through.
An error is caught by the try clause. After the code in the except block gets executed, the instructions in the [finally clause] would run.
Please note that a [finally block] will ALWAYS run, even if you’ve returned ahead of it.
try: # Intentionally raise an error. x = 1 / 0 except: # Except clause: print("Error occurred") finally: # Finally clause: print("The [finally clause] is hit")
Error occurred The [finally clause] is hit
Use the As keyword to catch specific exception types
With the help of the “as” keyword, we can create a new exception object inline.
Here, in the below example, we are creating the IOError object and then using it in the exception block.
try: # Intentionally raise an error. f = open("no-file") except IOError as err: # Creating IOError instance for book keeping. print("Error:", err) print("Code:", err.errno)
('Error:', IOError(2, 'No such file or directory')) ('Code:', 2)
Best practice for manually raising exceptions
Avoid raising generic exceptions because if you do so, then all other more specific exceptions have to be caught also. Hence, the best practice is to raise the most specific exception close to your problem.
Bad example.
def bad_exception(): try: raise ValueError('Intentional - do not want this to get caught') raise Exception('Exception to be handled') except Exception as error: print('Inside the except block: ' + repr(error)) bad_exception()
Inside the except block: ValueError('Intentional - do not want this to get caught',)
Best Practice:
Here, we are raising a specific type of exception, not a generic one. And we are also using the args option to print the incorrect arguments if there are any. Let’s see the below example.
try: raise ValueError('Testing exceptions: The input is in incorrect order', 'one', 'two', 'four') except ValueError as err: print(err.args)
('Testing exceptions: The input is in incorrect order', 'one', 'two', 'four')
How to skip through errors and continue execution
Ideally, you shouldn’t be doing this. But if you still want to do it, then follow the below code to check out the right approach.
try: assert False except AssertionError: pass print('Welcome to Prometheus. ')
Now, have a look at some of the most common Python exceptions and their examples.
Most common exception errors
- IOError – It occurs on errors like a file failing to open.
- ImportError – If a Python module can’t be loaded or located.
- ValueError – It occurs if a function gets an argument of the right type but an inappropriate value.
- KeyboardInterrupt – It gets hit when the user enters the interrupt key (i.e. Control-C or Del key)
- EOFError – It gets raised if the input functions (input()/raw_input()) hit an end-of-file condition (EOF) but without reading any data.
Examples of most common exceptions
ex_list = [IOError, ValueError, ImportError, EOFError, KeyboardInterrupt, any] for ex in ex_list: try: raise ex except IOError: print('1. Error occurred while opening the file.') pass except ValueError: print('2. Non-numeric input detected.') pass except ImportError: print('3. Unable to locate the module.') pass except EOFError: print('4. Identified EOF error.') pass except KeyboardInterrupt: print('5. Wrong keyboard input.') pass except: print('6. An unknown error occurred.') pass
Summary – How to Best Use Try-Except in Python
while programming, errors are bound to happen. It’s a fact that no one can ignore. And there could be many reasons for errors like bad user input, insufficient file permission, the unavailability of a network resource, insufficient memory, or most likely the programmer’s mistake.
Anyways, all of this can be handled if your code uses exception handling and implement it with constructs like try-except, tr-except-else, and try-except-finally. Hope, you would have enjoyed reading the above tutorial.
If you liked the post, then please don’t miss to share it with friends and on your social media accounts.
Best,
TechBeamers.