Exception Handling
Rushikesh J.
QA Automation Engineer @Vinz Global | Robot Framework | Manual Testing, Automation Testing | Python | Selenium | GIT | JIRA | Immediate Joiner | API Testing Using Postman | Jenkins
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