Exception Handling in Python

Exception Handling in Python

Β·

5 min read

Namaste Coders πŸ‘©β€πŸ’»

In this article, we will discuss exception handling in Python.

What is Exception Handling?

It can be said as a tool that allows a programmer to handle potentially occurring errors gracefully πŸ‘§

Errors are part of programming. Errors are categorized as following in programming world πŸ‘‡

  • Syntax Error: this error occurs when you write your code syntactically wrong. ex: missing colon(:) after if.
  • Logical Error: this error occurs when your program does not provide the expected output. ex: 2+3=5 is expected but program returns 23.

  • Runtime Error: this error occurs when user enters wrong input due to which for a particular input program doesn’t work properly. This is the error where we need to handle exceptions. ex: user enters 5/0 which return divisionByZeroError.

errors.jpeg

In this section, we will learn new keywords try, except, raise, finally.

try block

As the name suggests, try means to try the set of codes. if it is correct try block executes otherwise except block will take in exception and handle it accordingly.

Syntax

try:
  #code block

except:
  #handle exception

Example

We want to open a file in your program which might not exist. For the sake of good code, do write the code using exception handling which will protect the system. You can put that in try except block to save your program from crashing.

# Exception Handling
try:
    file=open('test1.txt','r')
    print("Success in reading")
except Exception as e:
    print(e)

print("After try except block code")


#Output:
#[Errno 2] No such file or directory: 'test1.txt'
#After try except block code

The error provided is not much clear, so we can provide a custom message as follows πŸ‘‡

try:
    file=open('test1.txt','r')
    print("Success in reading")
except Exception as e:
    print("File does not exist")

print("After try except block code")

#Output
#File does not exist
#After try except block code

Exceptions are of various different types and occurs according to the error caused. Following is the List of various exceptions and their meaning

image.png

If we know when and what error can be caused according to it we can handle the exception . If we don’t know the type of exception then we can use BaseException which can be used for all the exceptions.

A hierarchy of Exceptions is present which you can see below πŸ‘‡

image.png

😎 all classes are extending from BaseException 🀟

try:
    file=open('test1.txt','r')
    print("Success in reading")
except IOError as e:
    print("File does not exist")

print("After try except block code")

#Output
#File does not exist
#After try except block code

In above example, file was not present at the path mentioned, thus flow went to except block.

Another Example

num1=5
num2=0
try:
    print("trying to divide num1 and num2")
    num1/num2
except ZeroDivisionError as err:
    print("You cannot divide by 0")
except Exception as err:
    print("All other exceptions are handeled")

#Output
#trying to divide num1 and num2
#You cannot divide by 0

In above example, print statement in the try block gets executed. num2 value is zero, thus it throws an error while dividing by 0. As a result except block statements are executed.

else in exception

It is opposite of exception. In a program either exception block will execute or else block will execute. Both of them cannot execute simultaneously.

num1=5
num2=0
try:
    num1/num2
except ZeroDivisionError as err:
    print("You cannot divide by 0")
else:
    print("There is no exception")

print("Outside")

#Output
#You cannot divide by 0
#Outside

In above code else block will not execute as there was exception

num1=5
num2=2
try:
    res=num1/num2
    print("answer is: ",res)
except ZeroDivisionError as err:
    print("You cannot divide by 0")
else:
    print("There is no exception")

print("Outside")


#Output
#answer is:  2.5
#There is no exception
#Outside

In above program as there was no exception so it gave answer in output, also else block executed in this case.

finally keyword

We can use finally with try except. As name suggest all the code written inside finally block will execute either there is any exception or not.

When there is no exception

num1=5
num2=2
try:
    res=num1/num2
    print("answer is: ",res)
except ZeroDivisionError as err:
    print("You cannot divide by 0")
else:
    print("There is no exception")
finally:
    print("I am inside finally block")
    print("Task Completed")

print("Outside")


#answer is:  2.5
#There is no exception
#I am inside finally block
#Task Completed
#Outside

When there is exception

num1=5
num2=0
try:
    res=num1/num2
    print("answer is: ",res)
except ZeroDivisionError as err:
    print("You cannot divide by 0")
else:
    print("There is no exception")
finally:
    print("I am inside finally block")
    print("Task Completed")

print("Outside")

#You cannot divide by 0
#I am inside finally block
#Task Completed
#Outside

raise keyword

There are various exceptions raised, we can also raise exceptions by using keyword raise. Using raise we can manually raise an exception.

syntax:
raise exception_name
name=input("Enter your name: ")

if name.isnumeric():
    raise Exception ("Numbers not allowed")
print("Welcome! ", name)

output

Enter your name: 5

Traceback (most recent call last): File "c:/Users/meenu garg/Desktop/Python/PythonCodes/Exception Handling/exceptions1.py", line 39, in raise Exception ("Numbers not allowed") Exception: Numbers not allowed

Another example

#raising exception inside exception
name=input("Enter your name: ")

try:
    print(age)
except Exception as e:
    if name =="Joe":
        print("You are not allowed")
    print("age is not defined : ",e)

output

Enter your name: Joe

You are not allowed

age is not defined : name 'age' is not defined

The End

I hope you enjoyed the article and had a good learning experience.

Follow for more articles and keep sharingπŸ‘©

Keep coding

Python blogs

Linkedin

hashnode blogs

Did you find this article valuable?

Support akshita garg by becoming a sponsor. Any amount is appreciated!

Β