Exception Handling | Python
In the previous article, we learnt about what is an exception and brief idea about it. In this article, we will learn how to handle the exceptions in python. When these exceptions occur, it causes the current process to stop and passes it to the calling process until it is handled. If not handled, our program will crash. If the exception never handled then our program will be stopped unexpectedly.
How to catch exceptions in Python?
We can handle exception using try statement. An operation which can raise exception written in a try block and the code which we want to execute once we encounter the exception is written in except block.
Syntax:
try:
code which can raise exception
except [exception]:
code to handle exception
Example:
try: print 1/(5-5) except: print "You made a mistake. You can't divide by zero"
Output:
You made a mistake. You can't divide by zero
In the above example, we have divided the 1 by zero which raised an exception and the code written in except block is got executed.
Catching Specific Exceptions:
In our previous example, we did not mention any specific exception in the except block. But this does not imply a good programming practice. As the good programming practice is to handle each possible exception meaningfully. The try block can have multiple except block to handle each exception differently and only one of the matching except block will be executed when an exception occurs.
We can use a tuple of values to specify multiple exceptions in an except clause. Here is an example pseudo code.
try: # Have your actual business logic pass except ValueError: # handle ValueError exception pass except (TypeError, ZeroDivisionError): # This handles multiple exceptions TypeError and ZeroDivisionError pass except: # handle all other exceptions pass
Raising Exceptions:
You can also raise your exception forcefully using the keyword Raise. We can also pass the exception message along with it to have the cause of the exception.
Syntax:
raise NameOfTheException("Exception message")
Example:
try: a= -2 if a < 0: raise ValueError("a is not a positive number!") except ValueError as ve: print(ve)
Output:
a is not a positive number!
Try … except … else clause:
The else clause in a
Syntax:
try:
code for try block
except:
code to handle exception goes here…
else:
code you want to execute if no error raised from try block
Try With finally Clause:
We can also use optional finally clause along with the try block. The block of code in
Syntax:
try:
code for try block
except:
code to handle exception goes here…
finally:
any tasks you want to execure regard less of error occurred or not. ex: Releasing db connection
Example:
try: f = open("test.txt","a") # Some more code for file manipulation... finally: f.close()
In the above example, we want to close the file if any error occurs during I/O operations.
That's all for handling exceptions for now. It is always good practice to handle the exceptions in a way that user gets meaningful error messages and can act based on that. Even a good error handling will prevent your code from breaking but one should remember that putting every bit of code in
That's all for this topic. If you guys have any suggestions or queries, feel free to drop a comment. We would be happy to add that in our post. You can also contribute your articles by creating contributor account here.
Happy Learning 🙂
If you like the content on CodePumpkin and if you wish to do something for the community and the planet Earth, you can donate to our campaign for planting more trees at CodePumpkin Cauvery Calling Campaign.
We may not get time to plant a tree, but we can definitely donate ₹42 per Tree.
About the Author
Tags: python
Comments and Queries
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:<pre><code class="java"> String foo = "bar"; </code></pre>For more information on supported HTML tags in disqus comment, click here.