- Introduction to Exceptions
- Handling Exceptions with try and except
- The else and finally Clauses
- Raising Exceptions
- Creating Custom Exceptions
- Summary
- Tasks
An exception is an error that occurs during the execution of a program. When an exception occurs, the normal flow of the program is disrupted, and the program terminates abnormally. Exception handling is a mechanism to handle runtime errors, ensuring the program continues to run smoothly.
print(x)
Output:
NameError: name 'x' is not defined
Explanation: The above code raises a NameError
because the variable x
is not defined.
The try
block lets you test a block of code for errors. The except
block lets you handle the error.
try:
print(x)
except NameError:
print("Variable x is not defined")
Output:
Variable x is not defined
Explanation: The try
block contains code that might raise an exception. The except
block contains code that runs if an exception occurs.
try:
n = int(input("Enter a number: "))
print(n)
except ValueError:
print("Please enter a valid integer")
except NameError:
print("Variable is not defined")
Output:
Enter a number: abc
Please enter a valid integer
Explanation: The code handles both ValueError
and NameError
exceptions.
a = [0, 1, 3, 5, 10]
x = 20
for i in a:
try:
print(x / i)
except ZeroDivisionError:
print("Division by zero is not allowed")
Output:
Division by zero is not allowed
20.0
6.666666666666667
4.0
2.0
Explanation: The code handles the ZeroDivisionError
exception when dividing by zero.
The else
block lets you execute code if no exceptions were raised. The finally
block lets you execute code regardless of whether an exception was raised or not.
a = [1]
x = 20
for i in a:
try:
print(x / i)
except ZeroDivisionError as e:
print(e)
else:
print("Success")
Output:
20.0
Success
Explanation: The else
block runs if no exceptions were raised in the try
block.
a = [1]
x = 20
for i in a:
try:
print(x / i)
except ZeroDivisionError as e:
print(e)
finally:
print("End")
Output:
20.0
End
Explanation: The finally
block runs regardless of whether an exception was raised or not.
You can raise an exception using the raise
keyword.
x = '10'
if type(x) is not int:
raise TypeError('Only integers are acceptable')
Output:
TypeError: Only integers are acceptable
Explanation: The code raises a TypeError
if x
is not an integer.
You can create custom exceptions by defining a new class that inherits from the built-in Exception
class.
class CustomError(Exception):
def __init__(self, message):
self.message = message
try:
raise CustomError("This is a custom error")
except CustomError as e:
print(e.message)
Output:
This is a custom error
Explanation: The CustomError
class inherits from the Exception
class. The code raises a CustomError
and handles it in the except
block.
In this chapter, we covered exception handling, including the try
and except
blocks, the else
and finally
clauses, raising exceptions, and creating custom exceptions.
- Write a program that handles a
ZeroDivisionError
when dividing two numbers. - Write a program that handles multiple exceptions, such as
ValueError
andTypeError
. - Write a program that uses the
else
andfinally
clauses in exception handling. - Write a program that raises a custom exception if a condition is not met.
- Create a custom exception class and use it in a program.