Exception Handling

Exception Handling

Error in Python can be of two types i.e.Syntax errors and Exceptions. Errors are problems in a program due to which the program will stop the execution. On the other hand, exceptions are raised when some internal events occur which change the normal flow of the program.?

Different types of exceptions in python:

  • SyntaxError: This exception is raised when the interpreter encounters a syntax error in the code, such as a misspelled keyword, a missing colon, or an unbalanced parenthesis.

if:

#Output
    if:
      ^
SyntaxError: invalid syntax        

  • TypeError: This exception is raised when an operation or function is applied to an object of the wrong type, such as adding a string to an integer.

x = 5
y = "hello"
z = x + y

#output
    z = x + y
        ~~^~~
TypeError: unsupported operand type(s) for +: 'int' and 'str'        

  • NameError: This exception is raised when a variable or function name is not found in the current scope.

for i in range(x):
    print(i)

#Output
    for i in range(x):
                   ^
NameError: name 'x' is not defined        

  • IndexError: This exception is raised when an index is out of range for a list, tuple, or other sequence types.

test_list = [1, 2, 3, 4]
print(test_list[4])

#Output
    print(test_list[4])
          ~~~~~~~~~^^^
IndexError: list index out of range        

  • KeyError: This exception is raised when a key is not found in a dictionary.

ages = {'Sagar': 30, 'Vishal': 28, 'Navaj': 33}
ages['Rushikesh']

#Output

    ages['Rushikesh']
    ~~~~^^^^^^^^^^^^^
KeyError: 'Rushikesh'        

  • ValueError: This exception is raised when a function or method is called with an invalid argument or input, such as trying to convert a string to an integer when the string does not represent a valid integer.

a = "Rushikesh"
b = int(a)

#Output
    b = int(a)
        ^^^^^^
ValueError: invalid literal for int() with base 10: 'Rushikesh'        

  • AttributeError: This exception is raised when an attribute or method is not found on an object, such as trying to access a non-existent attribute of a class instance.

X = 10
X.append(6)

#Output
    X.append(6)
    ^^^^^^^^
AttributeError: 'int' object has no attribute 'append'        

  • ZeroDivisionError: This exception is raised when an attempt is made to divide a number by zero.

c = 5/0

#output
    c = 5/0
        ~^~
ZeroDivisionError: division by zero        

  • FileNotFoundError: FileNotFoundError is an exception in Python that is raised when a program tries to access a file that doesn’t exist.

file1 = open("abc.txt")

#Output
    file1 = open("abc.txt")
            ^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'abc.txt'        

  • IndentationError: An Indentation error is a compile-time error that occurs when tabs or spaces in a code do not follow expected patterns.

for i in range(10):
print(i)

#Output
    print(i)
    ^
IndentationError: expected an indented block after 'for' statement on line 32        

Try And Except:

try : This block handles the error in our code if any of it exist

except : This block gives the output that you want to show if your code is faulty.

a = 5
b = 0
try:  #this part of the code will try to execute if there is error in try block then only except block will be execute 
    print(a/b)
except:
    print("There is an error")

#Output
There is an errro        
a = 5
b = 2
try:  
#this part of the code will try to execute if there is error in try        #block then only except block will be execute
    print(a/b)
except:
    print("There is an error")

#Output
2.5        

if we want to print the exact exception that occurred? We can do this by assigning the Exception to a variable right in front of the except keyword.

When you do this and print the Exception to the terminal, it is the value of the Exception that you get.

a = 5
b = 0
try:  
    print(a/b)
except Exception as e:
    print("There is an error ------ ",e)

#Output
There is an error ------  division by zero        

Else And Finally:

else: The else block lets you execute code when there is no error.

a = 5
b = 2
try:
    print(a/b)
except Exception as e:
    print("There is an error ------ ",e)
else:
    print("No Error")

#Output
2.5
No Error        

finally : The finally block lets you execute code, regardless of the result of the try- and except blocks

#with Error
a = 5
b = 0
try:
    print("Opem file")
    print(a/b)
except Exception as e:
    print("There is an error ------ ",e)
else:
    print("No Error")
finally:
    print("close file")

#Output
Opem file
There is an error ------  division by zero
close file        
#Without Erro
a = 5
b = 2
try:
    print("Opem file")
    print(a/b)
except Exception as e:
    print("There is an error ------ ",e)
else:
    print("No Error")
finally:
    print("close file")


#Output
Opem file
2.5
No Error
close file
        

要查看或添加评论,请登录

Rushikesh J.的更多文章

  • Linux Operating System

    Linux Operating System

    Linux Operating System ======================= => Linux is a community based OS => Linux is free & Open Source => Linux…

  • Infrastructure

    Infrastructure

    ================= Infrastructure ================= Servers (Machines) Databases Storage Network Security Backup =>…

  • Application Architectural Patterns

    Application Architectural Patterns

    =================================== 1) Monolithic Architecture (Outdated) 2) Microservices Architecture (Trending)…

  • DevOps Introduction

    DevOps Introduction

    =============== What is DevOps =============== DevOps = Development + Operations => DevOps is a culture/process in IT…

    2 条评论
  • Try and Exception in Python

    Try and Exception in Python

    Exception is the error and is an event, which occur when program statements are executing. It disrupts the flow of…

  • Python Array With Examples

    Python Array With Examples

    Array in Python Array in Python Array is the collection of items having same data type with contiguous memory location.…

  • Python Date Object

    Python Date Object

    We can work with time and date with Python. There are two module in Python time and datetime that used to work with…

  • String Formatting WITH Problems and Solution

    String Formatting WITH Problems and Solution

    What is String Formatting? It is the way to insert custom string or variable in a text (string). Using string…

  • SET Different Methods With Examples

    SET Different Methods With Examples

    SET Method : add() Working: This method is used to add element to set. Syntax: set.

  • Python SET Comprehension With Examples

    Python SET Comprehension With Examples

    What is Comprehension? ?We create a sequence from a given sequence is called comprehension. ?Sequence means list…

社区洞察

其他会员也浏览了