Exception handling in Python try except finally

Exception Handling in Python

In the previous chapter, we discussed Errors and Exceptions in Python. In this post, we will discuss Exception Handling and the usage of except block and assert statements in Python. We will also see how we can deliver a smoother experience to users by displaying appropriate messages whenever exceptions occur in a program.

Please find below the format of handling the exceptions in a Python program.

#Format of exceptions in Python programming
try:
  #statements that may cause error
except nameOfException:
  #statements to handle the exception
  #typically a message to display to the users
else:
  #this block executes when there is no error in try block
finally:
  #this block of code executes irrespective of
  #the occurrence of the error
  • We include the statements or the code block that may cause the error in the try block.
  • We use the except block to handle the exception by displaying some understandable messages to the user. If there are no errors in the try block, then the else block gets executed.
  • We use the finally block to execute a code set irrespective of whether an exception occurs or not.

Let us now look at a program to understand how we can implement this concept in a real-world programming scenario.

#Program to show exception handling in Python
try:
  f = open("somefile.txt","w")
  x,y = [int(i) for i in input("Enter two numbers: ").split()]
  z = x/y
  f.write("writing %d into somefile.txt"%z)
except ZeroDivisionError:
  print("Please do not divide by zero")
  print("Try entering numbers other than zero")
else:
  print("Good boy")
finally:
  f.close()
  print("File closed")
Output 1:

Enter two numbers: 14 2
Good boy
File closed

Output 2:

Enter two numbers: 5 0
Please do not divide by zero
Try entering numbers other than zero
File closed

In the program above, we tried opening a file and saving it with the result of the division of two numbers. In maths, you cannot divide any number by zero. The same is in the programming world as well. You cannot divide any number by zero, and the Python will throw you an exception called ZeroDivisionError if you try dividing any number by zero.

That’s why we added the code block involving the division in the try block of the program above. Because that’s where the actual attempt to find the result happens. Since this code block can cause the exception, ZeroDivisionError, we tried catching the exception using the except block as shown in the program above.

The except block catches the exception and also allows you to display messages to users regarding the exception. As mentioned earlier, the finally block gets executed irrespective of whether the exception occurs or not, as shown in the output above.

We tried running this program twice under two different scenarios. In the first scenario, we passed two integers, 14 and 2, and there were no exceptions, and the file was also successfully closed after printing the code from the else block. The else block was executed in the first scenario since no exceptions occurred in the try block of scenario 1. However, when we tried giving the second number as zero, it resulted in an exception and displayed the error messages from the except block. Since the finally block executes even when the exception occurs, it still printed “File Closed”, as shown in the output 2 above.

More info on the Except Block

As mentioned in this post, the ‘except‘ block helps catch the exceptions from the try block. The except block gets executed only when the try block causes an exception. We can use except block in the formats mentioned below.

We can use in the except block, the Exceptionclass name, which is raised in the try block. For example, in the program above, ZeroDivisionError is raised in the try block when the exception occurred, and therefore we used the same in the except block as well.

except ExceptionClass:

We can also catch the exception class as an object with a specific description of the exception.

except ExceptionClass as obj:

We can catch multiple exceptions by describing them in a tuple, as shown below.

except (Exceptionclass1, Exceptionclass2):

The assert statement

The assert statement is helpful to validate whether a specific condition is true or not. When it is invalid, the assert statement raises an error. Please refer below for the format of the assert statement.

assert condition, message

In cases when the condition fails, the exception is raised in the name of AssertionError, and a corresponding message available in the assert statement. If we do not define any message in the assert statement and if the condition fails, it will still raise an AssertionError without a message.

PYTHON PROGRAM OF ASSERT STATEMENT WITHOUT A MESSAGE

#Python program to show assert statement
#WITHOUT message in the assert statement
try:
  num = int(input("Enter a number between 7 and 14: "))
  assert num>=7 and num<=14
  print("The number entered is: ",num)
except AssertionError:
  print("The condition failed")
Output:

Enter a number between 7 and 14: 15
The condition failed

You can notice that it displayed only the print statement from the except block and did not show any message from the assert statement as we did not define any message in the assert statement.

PYTHON PROGRAM OF ASSERT STATEMENT WITH A MESSAGE IN THE ASSERT STATEMENT

#Python program to show assert statement
#WITH message in the assert statement
try:
  num = int(input("Enter a number between 7 and 14: "))
  assert num>=7 and num<=14, "Please enter the correct input"
  print("The number entered is: ",num)
except AssertionError as obj:
  print(obj)
Output:

Enter a number between 7 and 14: 15
Please enter the correct input

In the above program, we declared a message, “Please enter the correct input”, as a message in the assert statement. When an exception occurs in the program above, this message is passed as an object in the except block and the same gets printed on the output.

Scroll to Top