Python Try Except
The try block lets you test a block of code for errors.
The except block lets you handle the error.
The else block lets you execute code when there is no error.
The finally block lets you execute code, regardless of the result of the
try- and except blocks.
Exception Handling
When an error occurs, or exception as we call it, Python will normally stop
and generate an error message.
These exceptions can be handled using the try statement:
Example
The try block will generate an exception, because x is not defined:
try:
print(x)
except:
print("An exception occurred")
An exception occurred
Since the try block raises an error, the except block will be executed.
Without the try block, the program will crash and raise an error:
Example
This statement will raise an error, because x is not defined:
print(x)
Traceback (most recent call last):
File "demo_try_except_error.py", line 3, in <module>
print(x)
NameError: name 'x' is not defined
Many Exceptions
You can define as many exception blocks as you want, e.g. if you want to
execute a special block of code for a special kind of error:
Example
Print one message if the try block raises a NameError and another for other
errors:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Variable x is not defined
Else
You can use the else keyword to define a block of code to be executed if no
errors were raised:
Example
In this example, the try block does not generate any error:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Hello
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")
Something went wrong
The 'try except' is finished
This can be useful to close objects and clean up resources:
Example
Try to open and write to a file that is not writable:
try:
f = open("demofile.txt")
try:
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
except:
print("Something went wrong when opening the file")
Something went wrong when writing to the file
Raise an exception
As a Python developer you can choose to throw an exception if a condition
occurs.
To throw (or raise) an exception, use the raise keyword.
Example
Raise an error and stop the program if x is lower than 0:
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
Traceback (most recent call last):
File "./prog.py", line 4, in <module>
Exception: Sorry, no numbers below zero
The raise keyword is used to raise an exception.
You can define what kind of error to raise, and the text to print to the user.
Example
Raise a TypeError if x is not an integer:
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")
Traceback (most recent call last):
File "demo_ref_keyword_raise2.py", line 4, in <module>
raise TypeError("Only integers are allowed")
TypeError: Only integers are allowed
User-Defined Exception in Python
Exceptions need to be derived from the Exception class, either directly or indirectly.
Although not mandatory, most of the exceptions are named as names that end
in “Error” similar to the naming of the standard exceptions in python. For
example,
Python3
# A python program to create user-defined exception
# class MyError is derived from super class Exception
class MyError(Exception):
# Constructor or Initializer
def __init__(self, value):
self.value = value
# __str__ is to print() the value
def __str__(self):
return(repr(self.value))
try:
raise(MyError(3*2))
# Value of Exception is stored in error
except MyError as error:
print('A New Exception occurred: ', error.value)
Output
A New Exception occurred: 6
ASSERTION IN PYTHON :
assertion is the boolean expression that checks if the statement is True or False. If
the statement is true then it does nothing and continues the execution, but if the
statement is False then it stops the execution of the program and throws an error.
Python assert keyword Syntax
In Python, the assert keyword helps in achieving this task. This statement takes as
input a boolean condition, which when returns true doesn’t do anything and
continues the normal flow of execution, but if it is computed to be false, then it
raises an AssertionError along with the optional message provided.
Syntax : assert condition, error_message(optional)
Parameters:
condition : The boolean condition returning true or false.
error_message : The optional argument to be printed in console in case
of AssertionError
Returns: Returns AssertionError, in case the condition evaluates to false along with
the error message which when provided.
Python assert keyword without error message
This code is trying to demonstrate the use of assert in Python by checking whether
the value of b is 0 before performing a division operation. a is initialized to the value
4, and b is initialized to the value 0. The program prints the message “The value of
a / b is: “.The assert statement checks whether b is not equal to 0. Since b is 0, the
assert statement fails and raises an AssertionError.
Since an exception is raised by the failed assert statement, the program terminates
and does not continue to execute the print statement on the next line.
Python3
# initializing number
a = 4
b = 0
# using assert to check for 0
print("The value of a / b is : ")
assert b != 0
print(a / b)
Output:
The value of a / b is :
-------------------------------------------------------------------
--------
AssertionError Traceback (most recent
call last)
Input In [19], in <cell line: 10>()
8 # using assert to check for 0
9 print("The value of a / b is : ")
---> 10 assert b != 0
11 print(a / b)
AssertionError:
Python assert keyword with an error message
This code is trying to demonstrate the use of assert in Python by checking whether
the value of b is 0 before performing a division operation. a is initialized to the value
4, and b is initialized to the value 0. The program prints the message “The value of
a / b is: “.The assert statement checks whether b is not equal to 0. Since b is 0, the
assert statement fails and raises an AssertionError with the message “Zero Division
Error”.
Since an exception is raised by the failed assert statement, the program terminates
and does not continue to execute the print statement on the next line.
Python3
# Python 3 code to demonstrate
# working of assert
# initializing number
a = 4
b = 0
# using assert to check for 0
print("The value of a / b is : ")
assert b != 0, "Zero Division Error"
print(a / b)
Output:
AssertionError: Zero Division Error