Errors:
Unusual and unexpected situations that affect the normal flow of program execution. There are Two types of errors in Python:
- Syntax Error or Compile Time error : These errors occur before the program execution begins, i.e., at the time of compilation.
- Reason for this Error is while writing the code we don’t follow proper rules and structure of the language.
- program will not start executing until we correct all the syntax errors in our code.
def count():
for letter in 'Sam':
print(letter)
count()
# Output :
File "", line 3
print(letter)
^
IndentationError: expected an indented block
- This is due to the errors in our code which occur at run-time and compiler dosen't recognize such errors.
- Python Full list of built-in exception.
ZeroDivisionError: division by zero
num = 123 / 0
print(num)
IndexError: list index out of range
names=['Aman','Ram','Singh']
names[3]
Exception Handling :
When there is an exception occured in our program, the execution stops and it displays an error message. But if we can handle it, the program will not crash and execution will continue.
Exception Handling using try and except:
- The basic terminology and syntax used to handle errors in Python are the try and except statements. The code which can cause an exception to occur is put in the try block and the handling of the exception is then implemented in the except block of code. The syntax follows:
# Syntax :
try:
some operations here...
...
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
...
else:
If there is no exception then execute this block.
# Example :
names=['Aman','Ram','Singh']
try:
names[3]
except IndexError as e:
print(e)
else:
print("Name fetched Successfully")
# Output :
list index out of range
# Example : using sys module to print the exception
import sys
names=['Aman','Ram','Singh']
try:
names[3]
except:
print(sys.exc_info()
# Output :
(<class 'IndexError'>, IndexError('list index out of range'), <traceback object at 0x000002182A237AC0>)
# Example : else block
names=['Aman','Ram','Singh']
try:
names[2]
except IndexError as e:
print(e)
else:
print("Name : {name} fetched successfully.".format(name=names[1]))
# Output :
Name : Ram fetched successfully.
def inputint():
while True:
try:
val = int(input("Please enter an integer: "))
except:
print("The Number you entered was not an Integer !")
continue
else:
print("Great !! That's an Integer")
print(val)
break
finally:
print("This is finally block executed ")
inputint()
# Output :
Please enter an Integer : wq
The Number you entered was not an Integer !
This is finally block executed
Please enter an Integer : ?>LK
The Number you entered was not an Integer !
This is finally block executed
Please enter an Integer : 23
Great !! That's an Integer
23
This is finally block executed
throwing Exceptions in Python
In python, we can also raise an exception forcefully using raise keyword :
# raise an OSError :
raise OSError
raise OSError('There was an OS Error')
Creating our own exception type:
To create our own exception type while create a class we need to inherit Exception class or any other exception class.
To catch this type of exception we can use previous discussed method. (try-except)
class notfellingwell(Exception):
def __init__(self,temp):
self.temp = temp
def __str__(self, temp):
if(self.temp >=38):
return f'Your body temp is : {self.temp} . Take Rest!!'
try:
raise notfellingwell(40)
except:
print("Ignore this temp and enjoy your life!!")