Chapter-3 Error and Exception Handling
Chapter-3 Error and Exception Handling
title
RuntimeError: occurs when an error does not fall into any category.
NameError: raised when a variable is not found in the local or global scope.
Multiple excepts
In [6]: try:
# Code that might raise an exception
result = int('a') # This will raise a ValueError
except ValueError:
# Code to handle the ValueError
print("Error: Could not convert to integer!")
except Exception as e:
# Code to handle other exceptions
print("An error occurred:", e)
Use of Else
In [8]: try:
# Code that might raise an exception
result = 10 / 2
except ZeroDivisionError:
# Code to handle the exception
print("Error: Division by zero!")
else:
# Code to execute if no exceptions are raised
print("Result:", result)
Result: 5.0
Use of finally
In [10]: try:
# Code that might raise an exception
result = 10 / 2
except ZeroDivisionError:
# Code to handle the exception
print("Error: Division by zero!")
else:
# Code to execute if no exceptions are raised
print("Result:", result)
finally:
# Code that always runs
print("This will always execute, regardless of exceptions.")
Result: 5.0
This will always execute, regardless of exceptions.
Raising an Error
In [12]: x = -5
if x < 0:
raise ValueError("Number must be positive")
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[12], line 4
1 x = -5
3 if x < 0:
----> 4 raise ValueError("Number must be positive")
In [ ]: