Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is an Exception?
2.1.
Types of Exceptions
3.
Exception handling in Python
3.1.
try-except block
3.2.
try-except-else block
3.3.
Finally block 
4.
Raising an Exception
5.
Assertion Error
6.
Frequently Asked Questions
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Exception Handling in Python

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

During the execution of a program, an exception occurs, which interrupts the normal flow of instructions. Python scripts must handle exceptions immediately, or they terminate and quit when an exception occurs. Exceptions are Python objects that represent errors.

An error in Python can be either a syntax error or an exception. This article explains what Exception Handling is.

Also See, Floor Division in Python, Swapcase in Python

What is an Exception?

The programmer can handle an exception if it occurs at runtime. Python represents exceptions as classes.

Errors can be categorized into three types:

  • Compile-time error: Software can contain errors such as missing semicolons, incorrectly spelled keywords, or errors in syntax. These errors are called syntactical errors or compile-time errors.
  • Logical Error: A problem with a program that causes it to run inaccurately without causing the program to terminate abnormally.
  • Runtime Error: A runtime error happens when a program you're using or writing crashes or produces a wrong output. The program may not be able to function correctly.

 

In other words, as a developer, you need to address all these errors and prevent what a user can do wrong to cause the application to crash. The user is not only responsible for these errors but also the server, internet connection, database connection, etc. Exception Handling in Python means that the execution should not be halted even if you encounter an error or Exception.
Also See, leap year program in python

Recommended Topic, python packages

For example:

x=8
y=0
print(x/y)
print(“end”)


Output:


 

In this program, we can see that x/y = 8/0 gives ZeroDivisionError, but this won't be easy to understand by a normal user.

Another problem with your execution is that you stopped it in between, so the "end" didn't appear on the screen. 
 

To solve this problem we can use a try-except block like below:

x=8
y=0
try:    //try block
    print(x/y)
except Exception:    //except block
    print("Given number cannot be divided by Zero")    //Write the message for the user
print("end")


Output:

A try-except block allows you to avoid the termination of the code in between, and it also clarifies what the exact error is to the user.

Types of Exceptions

There are two types of Exceptions:

  1. Built-in Exception: 
    All built-in BaseException classes are based on this class already present in Python.

     
  2. User-Defined Exception: An Exception created by a programmer is known as a user-defined exception.
     

Also see, Fibonacci Series in Python and Convert String to List Python.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Exception handling in Python

Let us know go through the ways which will help us to handle the exceptions generated in python.

Also see, Python Filter Function

try-except block

To solve the problem of Exceptions, you can use a try-except block in which:

  • try: Exceptions raised in try will jump straight into the except Block.
  • except: Exceptions raised in try will only be handled by the except Block. Even if a try block contains only a pass statement, an except block is still required.
     

Syntax:

try:
    //Statements
except Exception:
    //Statements

 

Example:

Here is a program for opening a text file named newfile.txt.

try:
    with open('newfile.txt') as file:
        readfile= file.read()
except:
    print ("newfile.txt does not exist.")


Output:

try-except-else block

If there is no exception, then the else block will be executed. After the try Block, the else blocks are executed.

Example:

try:
    f = open('newfile.txt')
except IOError:
    print("newfile.txt doesn't exist")
else:
    print("File exists!")


If newfile.txt exists and opens correctly, an exception is not raised, and the else clause will be executed. If newfile.txt does not exist, the else clause will not be executed.

Output:

Finally block 

This is another example of exception handling. We can include a final block when we handle exceptions with the try and except Block. The finally Block is used to close file resources, close database connections, or display a message at the end of the program execution.

Example:

try:
    f = open('newfile.txt')
except IOError:
    print("newfile.txt doesn't exist")
else:
    print("File exists!")
finally:
    print("This statement will always gets executed.")


Output:

You can practice by yourself with the help of online python compiler.

Raising an Exception

Raising an exception is possible using raise. By using the raise statement, the programmer can force a specific exception to occur. Only one argument is passed to raise, indicating the exception to raise.

Example:

number = 12
if number < 20:
    raise Exception('number should be greater than 20') 


Output:

Assertion Error

In Python, an assert statement can be used to validate any condition within a program. The program will continue if the assertion is true. When the condition is False, we get the AssertionError. This disrupts the flow of the program.

Example:

try:
    assert "Ninja2022" == "Ninja2021" 
except AssertionError:
    print ("Some issue has occurred.")


Output:


 

Some points to remember: 

  • It is possible to write several except blocks for a single try block.
  • The try block can be written without ant except for blocks, but it has no meaning.
  • To handle multiple exceptions, we can write multiple except blocks.
  • It is impossible to write an except block without a try block.
  • It is optional to include an Else and Finally block.
  • Whether an exception occurs or not, the finally block is always executed.

 

You can also read about the Multilevel Inheritance in Python.

Frequently Asked Questions

  1. What is the purpose of exception handling?
    Maintaining the normal flow of an application is the key advantage of exception handling. We need to handle exceptions because they disrupt the normal flow of an application.
     
  2. Error handling vs. exception handling - what is the difference?
    In exception handling, exceptions can be handled at run time, whereas in error handling, errors cannot be handled as they are unchecked type. Exceptions are objects which derive from the System.
     
  3. What is the difference between final, finally, and finalize?
    Finally is the Block in Exception Handling, which gets executed every time, finalize is a method of the object class, and Final is an access modifier.
     
  4. What happens is an Exception is not handled.
    A program terminates suddenly when an exception occurs, which may cause the program to be corrupted. Data can be lost in the database or a file if an exception occurs. 

Conclusion

In this blog, we have seen how we can do Exception Handling in python using try-except, else, finally blocks, and how to raise an exception.

We hope that this blog has helped you enhance your knowledge about Exception Handling and if you would like to learn more, check out our articles on the link. Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass