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

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago