21.error handling
try
: This is the block of the code to be attempted(may lead to an error).except
: Block of code will execute in case there is an error in try block.finally
: A final block of code to be executed, regardless of an error.
Exception Handling
When an error occurs, python will normally stop and generate an error message.
These exceptions can be handled using try
statement.
Without error handling
print(x)
Output:
NameError: name 'x' is not defined
With error handling
try:
print(x)
except:
print("An exception occurred")
Output:
An exception occured
Without the try block, the program will crash and raise an error.
With try block, since the try block raises an error, the except block will be executed.
Many Exceptions
We can define as many exception blocks as we want e.g. if we want to execute a special block of code for a special kind of error.
Example
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Output:
Variable x is not defined
Else
We can use else
keyword to define a block of code to be executed if no errors were raised.
Using else block
try:
print("Python")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Finally
The finally
block, if specified, will be executed regardless if the try block raises an error or not.
Example
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Continue and Break
We can use continue and break statements, when we are using try..except blocks in a loop.
Example
while True:
try:
result = int(input('Please provide number: '))
except:
print('Whoops! That is not a number')
continue
else:
print('Yes Thank You')
break
finally:
print('End of try/except/finally')
print('I will always run at the end!')
Output:
Please provide number: b
Whoops! That is not a number
End of try/except/finally
I will always run at the end!
Please provide number: 1
Yes Thank You
End of try/except/finally
I will always run at the end!
Raise an exception
As a python developer, we can choose to throw an exception if a condition occurs
To throw or raise an exception, we use raise
keyword.
Example
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
Output:
Exception: Sorry, no numbers below zero
The above program raises an error and stop the program if x is lower than 0.
We can define the kind of error to raise, and the text to print to the user.
Example
x = "Bhavya"
if not type(x) is int:
raise TypeError("Only integers are allowed")
Output:
TypeError: Only integers are allowed