DEV Community

Guru prasanna
Guru prasanna

Posted on

Python Day - 33 Exception Handling

Exception Handling

--> Exception is an abnormal event that happens during the execution of the program and stops the program abruptly(Immediately)
--> Exception handling allows to respond to the error, instead of crashing the running program.

Syntax:

    try:
          # Code that might raise an exception
    except SomeException:
          # Code to handle the exception
    else:
         # Code to run if no exception occurs
    finally:
        # Code to run regardless of whether an exception occurs

Enter fullscreen mode Exit fullscreen mode

try, except, else and finally Blocks

1. try Block

  • The try block contains the code that may raise an exception.
  • If an exception occurs, it is passed to the except block.
    2. except Block

  • The except block handles exceptions that occur in the try block.

  • You can specify different types of exceptions or use a general except clause to catch all exceptions.

3. else Block (Optional)

  • The else block executes only if no exception occurs in the try block.

4. finally Block (Optional)

  • The finally block executes regardless of whether an exception occurs or not.
  • It is often used for cleanup actions like closing files or releasing resources.

Examples:

1)

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

Output:

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

2)

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

Output:

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

3)

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

Output:

#if all inputs are correct
Enter no.10
Enter no. 5
2
15

#if any error not specified particularly
Enter no.10
Enter no. 5
2
15
Something went wrong

#if ZeroDivisionError
Enter no.10
Enter no. 0
no2 should not be zero. Check no2 Value

#if ValueError
Enter no.10
Enter no. ten
Inputs should be numbers 
Enter fullscreen mode Exit fullscreen mode

Difference between exception handling and conditional statement:

Image description

** Note:**
--> Use try-except when dealing with unpredictable errors
--> Use if-else when handling expected conditions

Traceback Module:

The traceback module in Python is used to extract, format, and print error traceback information, helping in debugging and logging exceptions.

Image description

Example:1

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

Output:

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

Example:2

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

Output:

Enter no.10
Enter no. 10
1
20
Something went wrong
Traceback (most recent call last):
  File "/home/guru/Desktop/Guru/Python/user.py", line 7, in <module>
    f = open("pqrs.txt")
        ^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'pqrs.txt'
Check finally message
Enter fullscreen mode Exit fullscreen mode

Catching Multiple Specific Exceptions:
--> we can handle multiple exceptions in a single except block using a tuple.
--> using as we can give a variable name for the exception also.

traceback.print_exc(): It provides detailed error information (line number, error type, message).

Oops:

Example to display object's memory location:

class Employee:
    pass

emp1 = Employee()
emp2 = Employee()
print(emp1)
print(emp2)
Enter fullscreen mode Exit fullscreen mode

Output:

<__main__.Employee object at 0x730a36434110>
<__main__.Employee object at 0x730a36434080>
Enter fullscreen mode Exit fullscreen mode

The pass keyword means "do nothing" (a placeholder), so the class is currently empty (it has no attributes or methods).

__doc__(Docstring Attribute)

The __doc__ attribute is used to access the docstring of a class, function, module, or method. A docstring is a multi-line string that provides documentation about the object which is declared inside triple quotes(''' ''').

Example:

class Employee:
    '''This class is for creating employees'''
print(Employee.__doc__)
Enter fullscreen mode Exit fullscreen mode

Output:

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

Self keyword:
--> “self” is used to access and manipulate the instance variables and methods within a class.
--> Self represents the instance of the class.

Object-Specific

--> Defined using self.variable_name.
--> Unique for each object.

Example:1

class Employee:
    def work(self):
        print(self.empName, 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

Output:

Guru designing
Pritha development
Enter fullscreen mode Exit fullscreen mode

Example:2 class with 3 methods:

class Employee:
    organization = "infosys"
    def work(self):
        print(self.empName, self.job_nature, self.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"
emp1.work()
emp2.work()
Enter fullscreen mode Exit fullscreen mode

Output:

Guru designing infosys
Pritha development infosys
Enter fullscreen mode Exit fullscreen mode

class specific information:class-specific information refers to data that is shared among all instances (objects) of a class.

Example:

class Employee:
    def work(self):
        print(self.empName, self.job_nature, self.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"
Employee.organization = "Infosys"
emp1.work()
emp2.work()
Enter fullscreen mode Exit fullscreen mode

Output:

Guru designing Infosys
Pritha development Infosys
Enter fullscreen mode Exit fullscreen mode

Top comments (0)