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

Select a Random Element from a Stream

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

2 days ago

Estimate π Using Monte Carlo Method

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

3 weeks ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

3 weeks ago

Staircase Climbing Ways

There is a staircase with N steps, and you can ascend either 1 step or…

4 weeks ago

Autocomplete System Implementation

Build an autocomplete system that, given a query string s and a set of possible…

4 weeks ago

Job Scheduler Implementation

Design a job scheduler that accepts a function f and an integer n. The scheduler…

4 weeks ago