Explain Built-in Exceptions in Python
Every instance in Python must belong to a class derived from BaseException. Unrelated exception classes, even with identical names, are never considered equivalent. The interpreter or built-in functions can generate built-in exceptions.
1. BaseException
This serves as the fundamental class for all built-in exceptions, not intended for direct inheritance by user-defined classes. Instead, for user-defined classes, Exception is employed. This class generates a string representation of the exception using str(), incorporating the provided arguments. If no arguments are present, it returns an empty string.
Syntex
try:
...
except SomeException:
tb = sys.exc_info()[2]
raise OtherException(...).with_traceback(tb)
2. ArithmeticError
This class serves as the foundation for built-in exceptions associated with arithmetic errors, including OverflowError, ZeroDivisionError, and FloatingPointError.
try:
a = 100/0
print (a)
except ArithmeticError:
print ("Arithmetic Exception.")
else:
print ("Success")
Output
Success
3. LookupError
This class acts as the foundation for exceptions triggered when an invalid or missing key or index is used on a mapping or sequence. The exceptions raised include KeyError and IndexError.
try:
a = [a, b, c]
print (a[3])
except LookupError:
print ("Index out of bound.")
else:
print ("Success")
Conclusion
Built-in Exceptions in Python provide a standardized way to handle errors and exceptional situations, enhancing code reliability and readability. Understanding these exceptions aids in effective error handling and debugging within Python applications.