How to Make the Best Use of Try-Except in Python?
How to Make the Best Use of Try-Except in Python?

How to Make the Best Use of Try-Except in Python?

Exception handling is an important part of Python programming. Whenever a Python program encounters an error, it raises an exception that leads to an unexpected termination of the program. Therefore, handling these exceptions becomes necessary in the programming. The concept of Exception handling not only handles different types of errors or exceptions but also allows us to implement constraints and conditions in our program. In Python, we use try-except block for exception handling. In this article, we will see how to make the best use of try-except blocks in python. We will see how to write an efficient program using try-except with the help of some examples in python.

Raising Exceptions Manually Using Raise Keyword in Python

Python has built-in exceptions that are raised when there is an error. Python raises an exception when an error corresponding to that exception occurs. However, we can raise an exception even without an error. We use raise keyword to raise inbuilt exceptions manually. We raise exceptions manually to impose constraints and conditions in our program.

There are several cases in programming where our program is correct and will not throw any exception but it will not be logically correct. That means, the program will work fine but the output will be impractical or unrealistic. This happens due to invalid inputs or improper operations. In this case, we need to define proper constraints. Therefore, we use raise keyword to implement these constraints.

Let’s see an example. Here we are writing a program to calculate percentage from obtained marks out of total marks.

total_marks = 500
marks_obtained = 425
print("Total marks =", total_marks)
print("Marks obtained =", marks_obtained)
# calculating percentage obtained
percentage = marks_obtained/total_marks * 100
print("Percentage = {} %".format(percentage))

Output:

Total marks = 500
Marks obtained = 425
Percentage = 85.0 %

In the above example, the program is working fine and producing the right output. Now, let’s see what happens when the marks obtained are greater than the total marks.

total_marks = 400
marks_obtained = 500
print("Total marks =", total_marks)
print("Marks obtained =", marks_obtained)
# calculating percentage obtained
percentage = marks_obtained/total_marks * 100
print("Percentage = {} %".format(percentage))

Output:

Total marks = 400
Marks obtained = 500
Percentage = 125.0 %

In the above example, the program is working fine without any error or exception. However, we can see the output is impractical. The percentage should not be greater than 100. So, we can say that the program is logically incorrect. Therefore, we will use try-except block along with the raise keyword to raise an exception manually in python. For example,

try:
    total_marks = 400
    marks_obtained = 500
    print("Total marks =", total_marks)
    print("Marks obtained =", marks_obtained)
    # calculating percentage obtained
    if total_marks < marks_obtained:
        raise ValueError
    percentage = marks_obtained/total_marks * 100
    print("Percentage = {} %".format(percentage))

except ValueError:
    print("Error: Obtained marks must be less than or equal to total marks!")

Output:

Total marks = 400
Marks obtained = 500
Error: Obtained marks must be less than or equal to total marks!

Here, we can see that exception is thrown when total marks are less than obtained marks. The program raises ValueError manually and the except block handles the exception.

Using Custom Exceptions in Python

In Python, we can create our own exceptions. To make our custom exception we have to define a class for that exception. This class must be a derived class of Python built-in Exception class. By creating our exception we can impose constraints in our program that will prevent it from logical errors. In the previous section, we have seen a similar method but there we were using built-in exceptions. But here we are having custom exceptions and we will be giving a name to these exceptions. This will make our exception more meaningful and our program more understandable.

In the following example, we are defining an exception class InvalidMarksError by inheriting the Python Exception class. Here, whenever total marks are less than obtained marks, the program will raise the custom exception InvalidMarksError.

class InvalidMarksError(Exception):
    pass

try:
    total_marks = 400
    marks_obtained = 500
    print("Total marks =", total_marks)
    print("Marks obtained =", marks_obtained)
    if total_marks < marks_obtained:
        raise InvalidMarksError
    percentage = marks_obtained/total_marks * 100
    print("Percentage = {} %".format(percentage))

except InvalidMarksError:
    print("Error: Obtained marks must be less than or equal to total marks!")

Output:

Total marks = 400
Marks obtained = 500
Error: Obtained marks must be less than or equal to total marks!

Suggested Reading: When to Use Try-Except Instead of If-Else

Differentiating Between Errors Using Try-Except in Python

We know that our program raises different exceptions for different types of errors. We may or may not know which exception can be raised by our code. Also, there is a possibility that we want to handle our program differently for different exceptions. In these situations, we want to know which exception will our program throw. For each possible exception, we may want to change our execution part. Well, for that also we have a solution.

In Python, we can use multiple except clauses to handle multiple exceptions. Here, an exception is specified in front of each except clause. Whenever the exception is thrown its corresponding except block catches it and code inside that block gets executed.

Let’s see an example.

try:
    # opening a file
    file = open("filename.txt")

except NameError:
    print("Exception: NameError")
except SystemError:
    print("Exception: SystemError")
except OSError:
    print("Exception: OSError")
except:
    print("Unknown error occured!")

Output:

Exception: OSError

In the above example, we have differentiated NameError, SystemError, and OSError from other exceptions. We got OSError as the program could not found the specified file. Here, we should keep one thing in mind that the most general exception or except block without any mentioned exception should be specified in the last. We should write the most specific exception first. Otherwise, the program will generate syntax error due to the presence of unreachable code. For example,

try:
    # opening a file
    file = open("filename.txt")

except:
    print("Unknown error occured!")
except NameError:
    print("Exception: NameError")
except SystemError:
    print("Exception: SystemError")
except OSError:
    print("Exception: OSError")

Output:

  File "c:\Users\Piyush\Desktop\Python Programs\multiple_exc.py", line 3
    file = open("filename.txt")
    ^
SyntaxError: default 'except:' must be last

We can see that SyntaxError stating “default ‘except:’ must be last” is thrown by the program.

Grouping Exceptions Using Try-Except in Python

In Python, we can also handle multiple exceptions simultaneously. That means a single except block can handle all the specified exceptions at the same time. This is done by grouping all the exceptions. We need to specify all our exceptions inside the parenthesis in front of our except clause. For example,

try:
    # opening a file
    file = open("filename.txt")

except (NameError, SystemError, OSError):
    print("Exception: NameError/SystemError/OSError")
except:
    print("Unknown error occured!")

Output:

Exception: NameError/SystemError/OSError

The Finally Block in Python

In programming, some cases may arise where we want to execute a block of code irrespective of any exception. That means a particular task should be completed no matter which part of try-except works. In that case, we use finally block. Statements inside the finally block will be executed each time whether or not any exception occurs in the try block.

If there is no exception, the statements inside the try block are executed first and then the statements inside finally block are executed. And if there is an exception, the finally block is executed after except block.

Let’s take an example related to file handling. When we are performing file handling operations, we need to always close the file before the termination of the program. For this, we use finally block to write file closing code in it.

try:
    file = open("filename.txt", "w")
    file.write("Welcome to avidpython.com")

except IOError:
    print("IOError occured!")
except:
    print("Unknown error occured!")
finally:
    file.close()

Conclusion

In this article, we have seen how we can use try-except in Python. We have discussed raising exceptions manually, custom exceptions, differentiating exceptions, and grouping of exceptions. In the end, we have also seen the use of finally block in Python.

To learn more about python programming, you can read this article on list comprehension. You might also like this article on dictionary comprehension in Python.

Donate to Avid Python

Dear reader,
If you found this article helpful and informative, I would greatly appreciate your support in keeping this blog running by making a donation. Your contributions help us continue creating valuable content for you and others who come across my blog. 
No matter how big or small, every donation is a way of saying "thank you" and shows that you value the time and effort we put into writing these articles. If you feel that our article has provided value to you, We would be grateful for any amount you choose to donate. 
Thank you for your support! 
Best regards, 
Aditya
Founder

If you want to Pay Using UPI, you can also scan the following QR code.

Payment QR Code
Payment QR Code

Piyush Sharma

Third-year computer engineering student inclined towards the latest trends and technology. Always keen to explore and ready to learn new things. To read more articles on Python, stay tuned to avidpython.com.

Leave a Reply