An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
Syntax Error: The name suggests that this error results from incorrect syntax. It leads to the termination of the program.
age = 18
if age >= 18
print("The person is eligible to vote.")
if age >= 18
^
SyntaxError: expected ':'
Here in the above example, we forgot the colon (:
) after the if
conditional statement, that's why we got the syntax error in the output.
Exceptions: Exceptions are raised when the program is syntactically correct, but the code results in an error. This error does not stop the execution of the program, however, it changes the normal flow of the program.
number = 20
division = number / 0
print(division)
division = number / 0
ZeroDivisionError: division by zero
In the above example, we got a zero division error exception, because we are trying to divide a number by 0
, in mathematics, we can not divide a number by 0
.
The try
and except
statements are used to catch and handle exceptions in Python.
Statements that can raise exceptions are kept inside the try
block, and the statements that handle the exception are written inside except
blocks.
try:
number = 20
division = number / 0
print(division)
except:
print("division by zero not allowed.")
division by zero not allowed.
Here, by using try
and except
block statements, we successfully handled the zero division error exception.
But, if there is no exception in the program, then the program runs smoothly and does not raise any exceptions.
try:
number = 20
division = number / 10
print(division)
except:
print("division by zero not allowed.")
2.0
Now, we are dividing a number by 10
, then in this case, there is no exception, so the program runs smoothly and prints the division number in the output.
You can mention which exception you want to catch in the except block
try:
number = 20
division = number / 0
print(division)
except ZeroDivisionError:
print("division by zero not allowed.")
division by zero not allowed.
Here in the above example, we mentioned the zero division error exception (ZeroDivisionError
) class name in the except
block.
When in the program, a zero division error exception occurs, then the except
block will execute.
You can also display a Python return exception message like this.
try:
number = 20
division = number / 0
print(division)
except ZeroDivisionError as e:
print("Exception:", e)
Exception: division by zero
Here, in the above example, we displayed the Python returned exception message for zero division error.
A try
statement can have more than one except
blocks, to specify handlers for different exceptions.
But note that at most only one except
block is executed from the list.
try:
number = 20
division = number / 2
print("Result: " + division)
except ZeroDivisionError as e:
print("Exception:", e)
except TypeError as e:
print("Exception:", e)
Exception: can only concatenate str (not "float") to str
Here in the above example, we try to connect a string text with a number ("Result: " + division
), but we can't directly connect a string text with a number data type in Python, so in this case a type error exception will occur.
When no except
block is found in the multiple except
blocks list, then it raises an exception.
To avoid this, add a default except
block at the end of the list.
You can not add a default except
block at the beginning, because whenever an exception occurs, that default except
block will be executed and it doesn't go to the next except
blocks.
try:
number = 20
division = number / 2
print("Result:", division)
numbers_list = [0, 1, 2, 3, 4, 5]
print(numbers_list[10])
except ZeroDivisionError as e:
print("Exception:", e)
except TypeError as e:
print("Exception:", e)
except:
print("Exception occured.")
Result: 10.0
Exception occured.
Here in the above example, there are no except
block matches in the multiple exception list, in this case, it executed the default except
block.
You can also add an Exception
class name in the except
block.
The Exception
class is the base class for all the exceptions in Python.
try:
number = 20
division = number / 2
print("Result:", division)
numbers_list = [0, 1, 2, 3, 4, 5]
print(numbers_list[10])
except ZeroDivisionError as e:
print("Exception:", e)
except TypeError as e:
print("Exception:", e)
except Exception as e:
print("Exception:", e)
Result: 10.0
Exception: list index out of range
Here, you can see the Exception
class name is added with the default except
block.
In Python, you can also use the else
block on the try
-except
block, and it must be present after, all the except blocks.
The code enters the else
block and executes only if the try
block does not raise an exception.
try:
number = 20
division = number / 2
print(division)
except ZeroDivisionError as e:
print("Exception:", e)
else:
print("Else block")
10.0
Else block
Here in the above example, you can see that the program does not contain any exception, and it printed the number division and "Else block"
text message.
Python provides a keyword finally
, which is always executed after the try
and except
blocks.
The finally
block always executes after the normal termination of the try
block, or after the try
block terminates due to some exception.
try:
number = 20
division = number / 2
print(division)
except ZeroDivisionError as e:
print("Exception:", e)
finally:
print("Finally block")
10.0
Finally block
The above example does not have any exceptions, and it printed the number division and "Finally block"
text message.
The finally
block executes after the try
block terminates due to some exceptions.
try:
number = 20
division = number / 0
print(division)
except ZeroDivisionError as e:
print("Exception:", e)
finally:
print("Finally block")
Exception: division by zero
Finally block
The above example raises a zero division error exception, so in the output, the zero division error exception message and "Finally block"
message are printed.
Python raise
Keyword is used to raise exceptions or errors.
The raise
keyword raises an error and stops the control flow of the program.
It is used to bring up the current exception in an exception handler so that it can be handled further up the call stack.
number = 5
if number % 2 != 0:
raise Exception("The number should not be an odd integer number.")
Exception: The number should not be an odd integer number.
Here in the above example, if the number is odd, we raised an exception.