Python try…except (Exception Handling)

In this tutorial, you will learn to handle exceptions in Python using try, except, and finally statements with the help of examples

Exceptions occur when there are logical errors in our program. For example, dividing a number by zero.

Exception handling is the process of handling exceptions in a custom way (rather than showing the default error message).


Python try…except Statement

We can handle exceptions in Python using the try statement. Our main program is placed inside the try clause, and the code that handles the exceptions is written in the except clause.

Here is the syntax:

try:
    # code that may cause exception
except:
    # code to run when exception occurs

With the try…except statements, we can choose what operations to perform once we have caught an exception.

For example,

try:
    numerator = int(input("Enter numerator: "))
    denominator = int(input("Enter denominator: "))

    result = numerator/denominator

    print(result)
except:
    print("Denominator cannot be 0. Try again.")

print("Program ends")

Here,

  • The try block has the actual code, which takes two input numbers - numerator and denominator and divides them.
  • When you enter 0 as the input value of the denominator, the program throws an error message present in the except block of the program.

One issue with the code above is that the except block displays the error message

"Denominator cannot be 0. Try again."

in case of all types of exceptions.

We can fix this by mentioning the type of exception that we want the except block to catch.

try:
    numerator = int(input("Enter numerator: "))
    denominator = int(input("Enter denominator: "))

    result = numerator/denominator

    print(result)

except ZeroDivisionError:
    print("Denominator cannot be 0. Try again.")
    print("Program ends")

User-defined Exceptions in Python

We can raise exceptions manually in Python using the raise keyword. For example,

try:
    a = int(input("Enter a positive integer: "))
    if a 

In the above example, the try block raises a custom ValueError exception when the input number is not positive.

Similarly, the except block prints the content of the ValueError exception.


Python try with else Clause

There are some situations where Python programmers might want to run some other block of code if the code inside the try block runs successfully.

We can do this by using the else clause. For example,

try:
    num = int(input("Enter a number: "))
    assert num % 2 == 0
except:
    print("Not an even number!")
else:
    reciprocal = 1/num
    print(reciprocal)

Here,

  • The program prints the reciprocal of the input number if it is an even number.
  • The program prints the except block, i.e., "Not an even Number!" if the input number is not even.

Python try with finally Clause

Python has a finally clause that we can use with the try statement. The finally clause is always executed (doesn't matter exceptions occur or not).

For example,

try:
   f = open("test.txt",encoding = 'utf-8')
   # perform file operations
finally:
   f.close()

Here,

  • We have opened a file named test.txt and performed some file operations on it in the try block.
  • The finally block has the f.close() function to close the file no matter what.
Did you find this article helpful?