DEV Community

Lakshmi Pritha Nadesan
Lakshmi Pritha Nadesan

Posted on

Day 33 - Exception Handling, OOPS Examples

Exception Handling:

What is Exception:

Exception is an abnormal event that happens during the execution of the program and stops the program abruptly(Immediately).

In Python, exception handling allows you to handle errors that may occur during the execution of a program. This is done using try, except and finally blocks.

The most common form of exception handling is using the try and except blocks.

try:
    no1 = int(input("Enter no."))
    no2 = int(input("Enter no. "))
    print(no1 + no2)
    print(no1 // no2)
    print(no1 * no2)
except ZeroDivisionError:
    print('Check no2 ')

Enter fullscreen mode Exit fullscreen mode
Enter no.100
Enter no. 0
100
Check no2 
Enter fullscreen mode Exit fullscreen mode

In this example, the try block contains code that might raise an exception (like dividing by zero), and the except block catches the exception (ZeroDivisionError) and handles it (printing a message).

try:
    no1 = int(input("Enter no."))
    no2 = int(input("Enter no. "))
    print(no1//no2)
except ZeroDivisionError:
    print("no2 should not be zero. Check no2 Value ")
    no2 = int(input("Enter no. "))
    print(no1//no2)
print(no1+no2)
Enter fullscreen mode Exit fullscreen mode
Enter no.100
Enter no. 0
no2 should not be zero. Check no2 Value 
Enter no. 10
10
110
Enter fullscreen mode Exit fullscreen mode

The user is then prompted to input a new value for no2, and the division is attempted again with the updated value.

The sum will be printed with the final value of no2 whether the exception was caught or not.

try:
    no1 = int(input("Enter no."))
    no2 = int(input("Enter no. "))
    print(no1//no2)
except ZeroDivisionError:
    print("no2 should not be zero. Check no2 Value ")
print(no1+no2)

Enter fullscreen mode Exit fullscreen mode
Enter no.100
Enter no. 0
no2 should not be zero. Check no2 Value 
100
Enter fullscreen mode Exit fullscreen mode

If the user enters 0 for no2, the exception is handled, but after the exception, the final line print(no1 + no2) will still execute using the original no2 (which is 0).

try:
    no1 = int(input("Enter no."))
    no2 = int(input("Enter no. "))
    print(no1//no2)
except ZeroDivisionError:
    print("no2 should not be zero. Check no2 Value ")
except ValueError:
    print("Inputs should be numbers ")
print(no1+no2)

Enter fullscreen mode Exit fullscreen mode
Enter no.100
Enter no. ten
Inputs should be numbers 

Enter fullscreen mode Exit fullscreen mode

If the user enters a non-numeric value (e.g., a string like "ten"), a ValueError will be raised when you try to convert the input to an integer. The program will then print: "Inputs should be numbers".

try:
    no1 = int(input("Enter no."))
    no2 = int(input("Enter no. "))
    print(no1//no2)
    print(no1+no2)
    f = open("pqrs.txt")
except ZeroDivisionError:
    print("no2 should not be zero. Check no2 Value ")
except ValueError:
    print("Inputs should be numbers ")
except:
    print("Something went wrong")

Enter fullscreen mode Exit fullscreen mode
Enter no.100
Enter no. 10
10
110
Something went wrong
Enter fullscreen mode Exit fullscreen mode

The open("pqrs.txt") line attempts to open a file. If the file is not found, it will raise a FileNotFoundError, which will be caught by the generic except block.

try:
    no1 = int(input("Enter no."))
    no2 = int(input("Enter no. "))
    print(no1//no2)
    print(no1+no2)
    f = open("pqrs.txt")
except:
    print("Something went wrong")
Enter fullscreen mode Exit fullscreen mode
Enter no.100
Enter no. 10
10
110
Something went wrong
Enter fullscreen mode Exit fullscreen mode

The except block will catch any exception (e.g., ZeroDivisionError, ValueError, FileNotFoundError).

When an exception is caught, the program prints "Something went wrong", but it doesn't tell you which error occurred or provide any details about the error.

import traceback
try:
    no1 = int(input("Enter no."))
    no2 = int(input("Enter no. "))
    print(no1//no2)
    print(no1+no2)
    f = open("pqrs.txt")
    print(f.read())

except:
    print("Something went wrong")
    traceback.print_exc()

Enter fullscreen mode Exit fullscreen mode
Enter no.100
Enter no. 10
10
110
Something went wrong
Traceback (most recent call last):
  File "/home/prigo/Documents/Python_class/arg.py", line 7, in <module>
    f = open("pqrs.txt")
Enter fullscreen mode Exit fullscreen mode

traceback.print_exc() is a built-in function that prints detailed information about the most recent exception. This includes the type of exception, the line number where it occurred, and the call stack.
This helps with debugging, as you get a clear view of what went wrong.

import traceback
try:
    no1 = int(input("Enter no."))
    no2 = int(input("Enter no. "))
    print(no1//no2)
    print(no1+no2)
    f = open("pqrs.txt")
    print(f.read())
except (ValueError, ZeroDivisionError) as msg:
    print("Check ",msg)

except:
    print("Something went wrong")
    traceback.print_exc()

Enter fullscreen mode Exit fullscreen mode
Enter no.100
Enter no. 0
Check  integer division or modulo by zero

Enter no.100
Enter no. ten
Check  invalid literal for int() with base 10: 'ten'

Enter no.100
Enter no. 10
10
110
Something went wrong
Traceback (most recent call last):
  File "/home/prigo/Documents/Python_class/arg.py", line 7, in <module>
    f = open("pqrs.txt")
        ^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'pqrs.txt'

Enter fullscreen mode Exit fullscreen mode

You catch specific exceptions (ValueError and ZeroDivisionError) using except (ValueError, ZeroDivisionError) as msg. If any of these exceptions are raised, you print "Check" followed by the exception message (msg).

A generic except block is used to catch any other unexpected errors. If such an error occurs, you print "Something went wrong" and print the full traceback for debugging using traceback.print_exc().

import traceback
try:
    no1 = int(input("Enter no."))
    no2 = int(input("Enter no. "))
    print(no1//no2)
    print(no1+no2)
    f = open("pqrs.txt")
    print(f.read())
except (ValueError, ZeroDivisionError) as msg:
    print("Check ",msg)
except:
    print("Something went wrong")
    traceback.print_exc()
finally:
    print("Check finally message")
Enter fullscreen mode Exit fullscreen mode
Enter no.100
Enter no. 10
10
110
Rose is a beautiful flower
Today is friday
Happy day

Check finally message

Enter fullscreen mode Exit fullscreen mode

The finally block will always run, no matter what happens in the try and except blocks. It's commonly used for cleanup activities (e.g., closing files).

In your case, it will print "Check finally message" whether an exception is raised or not.

import traceback
try:
    print(10/0)
finally: 
    print("Check finally message")

Enter fullscreen mode Exit fullscreen mode
Check finally message
Traceback (most recent call last):
  File "/home/prigo/Documents/Python_class/arg.py", line 3, in <module>
    print(10/0)
          ~~^~
ZeroDivisionError: division by zero

Enter fullscreen mode Exit fullscreen mode

The finally block runs and prints "Check finally message".

Then, the ZeroDivisionError traceback is printed, showing that an error occurred during the execution of the code.

import traceback
try: 
    print(10/0)
finally:
    print("Check finally message")
except:
    print("except block")

Enter fullscreen mode Exit fullscreen mode
SyntaxError: invalid syntax
Enter fullscreen mode Exit fullscreen mode

Trying to combine try, finally, and except in a single block, but there's an issue with the structure of the code. Specifically, the finally block should always appear after the try block, and before the except block.

OOPS Example:

class Employee:
    pass

emp1 = Employee()
emp2 = Employee()
print(emp1)
print(emp2)
Enter fullscreen mode Exit fullscreen mode
<__main__.Employee object at 0x7ed15ffffe00>
<__main__.Employee object at 0x7ed15ffffd70>

Enter fullscreen mode Exit fullscreen mode

Employee class with no attributes or methods (just using pass).Then created two instances of the Employee class, emp1 and emp2, and printed them.

Here, the output shows the memory addresses of the two objects (the hexadecimal values after 0x), which are unique for each instance.

class Employee:
    ''' This class is for creating employees'''

print(Employee.__doc__)

Enter fullscreen mode Exit fullscreen mode
 This class is for creating employees
Enter fullscreen mode Exit fullscreen mode

Docstrings are used to describe the purpose and functionality of classes, methods, and functions in Python.

.doc is an attribute that stores the docstring of a class, method, or function.


import os
print(os.__doc__)
Enter fullscreen mode Exit fullscreen mode

The os.doc will give you a general description of the module's purpose.

class Employee:
    def work(self):
        print("Name:",self.empName, "work:",self.job_nature)

emp1 = Employee()
emp1.empName = 'Guru'
emp1.job_nature = "designing"
emp2 = Employee()
emp2.empName = "Pritha"
emp2.job_nature = "development"
emp1.work()
emp2.work()

Enter fullscreen mode Exit fullscreen mode
Name: Guru work: designing
Name: Pritha work: development

Enter fullscreen mode Exit fullscreen mode

Dynamically add two attributes (empName and job_nature) to the instances emp1 and emp2 after creating the objects. This is done by directly assigning values to emp1.empName and emp1.job_nature (and similarly for emp2).

When you call emp1.work() and emp2.work(), the method prints the values of empName and job_nature for each employee.

class Employee:

    def work(self):
        print("Name:",self.empName, "work:",self.job_nature, "Company name:",organization)
    def take_leave(self):
        pass
    def promote(self):
        pass

emp1 = Employee()
emp1.empName = 'Guru'
emp1.job_nature = "designing"
emp2 = Employee()
emp2.empName = "Pritha"
emp2.job_nature = "development"
organization = "infosys"
emp1.work()
emp2.work()
Enter fullscreen mode Exit fullscreen mode
Name: Guru work: designing Company name: infosys
Name: Pritha work: development Company name: infosys
Enter fullscreen mode Exit fullscreen mode

The organization variable is defined outside the class and is accessed globally in the work method. If the organization variable is not defined in the global scope, this will raise a NameError.

When you call emp1.work() and emp2.work(), the work method prints the employee's name and job nature along with the global organization variable, which is "infosys".

Top comments (0)