Python Exception Handling

Table Of Contents:

  1. What Is An Exception?
  2. Exception Handling Using Try And Except Block.
  3. Catching Specific Exception.
  4. Except Clause With Multiple Exceptions.
  5. Try With Else Block.
  6. Finally, Block In Exception Handling.
  7. Raise An Exception.
  8. Types Of Exceptions.

(1) What Is An Exception?

  • An exception is an unwanted event that occurred while your program was running.
  • When your program depends upon external factors like user inputs, and outside resources like files, folders etc, that is out of your control.
  • Sometimes users will enter random values, and sometimes file will not be present at the location where you are searching, your program will through an error that time and it will stop.
  • To handle those specific scenarios we use Python exception handling.

(2) Exception Handling Using Try and Except Block.

  • Try and Except statements are used to catch and handle exceptions in Python.
  • The code which can raise an exception is put under the “try” block, and the code which going to handle those exceptions is put under the “except” block.

Syntax:

try:
    #Vunerable Code
    
except:
    #Code For Exception Handling

Example-1: Without Exception Handling

num = int(input("Enter A Number"))
value = 100
divide = value / num
print(divide)
Output:
ZeroDivisionError                         Traceback (most recent call last)
Input In [73], in <cell line: 3>()
      1 num = int(input("Enter A Number"))
      2 value = 100
----> 3 divide = value / num
      4 print(divide)

ZeroDivisionError: division by zero

Example-2: With Exception Handling

try:
    num = int(input("Enter A Number"))
    value = 100
    divide = value / num
    print(divide)
except:
    print("Number Is Not Supported")
Output: 
Enter A Number 0
Number Is Not Supported

(3) Catching Specific Exceptions.

  • You can write different except blocks for different exceptions.
  • This allows us to handle different exceptions separately.
  • Please note that at most one expect block will be executed.

Syntax:

try:
    # statement(s)
except Exception I:
    # statement(s)
except Exception II:
    # statement(s)
    ......
    ......
except Exception n:
    # statement(s)

Example-1

try:
    # statement(s)
except Exception I:
    # statement(s)
except Exception II:
    # statement(s)
    ......
    ......
except Exception n:
    # statement(s)
Output:
division by zero

Example-2

try:
    a = 10
    b = a/x
    print(b)
    
except ZeroDivisionError as e:
    print(e)
    
except NameError as e:
    print(e)
Output:
name 'x' is not defined

(4) Except Clause With Multiple Exception.

  • You can also use the same except statement to handle multiple exceptions by separating exceptions with commas (, ).
  • You have to write all the exceptions inside the parenthesis ( ).

Syntax:

try:
    #Vunerable Code
    
except(Exception I, Exception II, ...... Exception n):
    #Code For Exception Handling

Example-1

try:
    a = 10
    b = a/0
    print(b)
    
except(ZeroDivisionError,NameError) as e:
    print(e)
Output:
division by zero

Example-2

try:
    a = 10
    b = a/0
    print(b)
    
except(ZeroDivisionError,NameError) as e:
    print(e)
Output:
name 'x' is not defined

(5) Try With Else Block.

  • You can use the else keyword to define a block of code to be executed if no errors were raised.

Example

try:
    print("Hello")
except:
    print("Something went wrong")
else:
    print("Nothing went wrong")
Output:
Hello
Nothing went wrong

(6) Finally Block On Exception Handling.

  • The try statement in Python can have an optional finally clause.
  • No matter what happens in the program this block will be executed.
  • It is generally used to release resources no matter whether your code is executed successfully or not.

Example

try:
    f = open("E:\Blogs\Python\demofile.txt",encoding = 'utf-8')
    
finally:
    f.close()

(7) Raise An Exception

  • In Python, an exception is raised when an error occurs when the program is running.
  • But, you can also manually raise an exception in Python.
  • The “raise” keyword is used to raise an exception in Python.

Example-1

try:
    raise NameError("I Am An Exception")
    
except NameError as e:
    print(e)
Output:
I Am An Exception

Example-2

try:
    num = int(input("Enter A Number: "))
    if num == 0:
        raise ZeroDivisionError('Exception Occured')
    else:
        print(num)
except ZeroDivisionError as e:
    print(e)
Output:
Enter A Number: 0
Exception Occured

Leave a Reply

Your email address will not be published. Required fields are marked *