Categories: python

Python Exception Handling – I

What is Python Exception Handling?

Exception handling is a Python concept used to handle exceptions and errors during program execution. Exceptions can be unexpected, or a developer may anticipate some disruption in the code flow due to an exception that may occur in a specific scenario. In either case, it must be addressed.

Try and Except Statement – Catching Exceptions:

Exceptions are caught and handled in Python using try and except code blocks. The code that can raise an exception is enclosed in the try clause, while the code lines that handle the exception are contained in the except clause.

The basic syntax is as follows:

try:
    # Some Code
except:
    # Executed if we get an error in the try block
    # Handle exception here

Example:


# initialize the amount variable
marks = 10000
  
# perform division with 0
a = marks / 0
print(a)

Here we will get an exception as output.

Output:

Traceback (most recent call last):
  File "<string>", line 6, in <module>
ZeroDivisionError: division by zero

Same example using try-except block.


# initialize the amount variable
marks = 10000
try:    
    a = marks / 0
    print(a)
except ZeroDivisionError:
    print("ZeroDivisionError Occurred and Handled")

Output:

ZeroDivisionError Occurred and Handled
Catching Multiple Exceptions :

Several approaches can be taken. We can either have multiple except blocks, each dealing with a different exception class, or we can handle multiple exception classes in a single except block.

Example:

# try block
try:
    num = int(input("Enter numerator number: "))
    denom= int(input("Enter denominator number: "))
    print("Result of Division: " + str(num/denom))
# except block handling division by zero
except(ZeroDivisionError):
    print("You have divided a number by zero, which is not allowed.")
# except block handling wrong value type
except(ValueError):
    print("You must enter integer value")

Output:

Enter numerator number: 23
Enter denominator number: 0
You have divided a number by zero, which is not allowed.

Enter numerator number: yu
You must enter integer value

Here, we are detecting a Particular Exception. A try statement can have multiple except clauses to specify handlers for various exceptions. Please keep in mind that only one handler will be executed.

Note: also read about Errors and Built-in Exceptions

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Recent Posts

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

1 hour ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

3 days ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

3 weeks ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

1 month ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

1 month ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

2 months ago