Python From Beginner to Advanced

0% completed

Previous
Next
Python - Built-in Exceptions

Python provides a number of built-in exceptions that handle different error cases. Understanding these exceptions is crucial for effective error handling and robust Python programming. Below is a table of some common built-in exceptions with rephrased descriptions, followed by examples demonstrating how to handle a couple of these exceptions.

#ExceptionDescription
1BaseExceptionThe superclass for all exceptions, serving as the base class for all other exceptions.
2StopIterationTriggered when an iterator's next() method signals that there are no further items.
3SystemExitTriggered by calling sys.exit(), signaling the interpreter to exit.
4StandardErrorObsolete in Python 3, it was the base class for all built-in exceptions except StopIteration and SystemExit.
5ArithmeticErrorSuperclass for exceptions that occur for errors in numeric calculations.
6OverflowErrorOccurs when a calculation exceeds a numeric type's designated limit.
7FloatingPointErrorOccurs when a floating point operation fails.
8ZeroDivisionErrorOccurs when division or modulo operation is performed with zero as the divisor.
9AssertionErrorTriggered when an assert statement fails.
10AttributeErrorOccurs when attribute reference or assignment fails.
11EOFErrorTriggered when no input is detected from input() or raw_input() and EOF is reached.
12ImportErrorOccurs when an import statement fails to find the module definition or cannot load it.
13KeyboardInterruptTriggered when the user interrupts program execution, typically with a Ctrl+C.
14LookupErrorBase class for errors that occur during a lookup.
15IndexErrorTriggered when an index is not found in a sequence.
16KeyErrorOccurs when a dictionary key is not found during lookup.
17NameErrorTriggered when a local or global name is not found.
18UnboundLocalErrorOccurs when a reference is made to a local variable in a function or method but no value has been assigned to it.
19EnvironmentErrorObsolete in Python 3; use OSError instead. Base class for I/O related errors.
20IOErrorObsolete in Python 3; integrated into OSError. Triggered for errors related to I/O operations.
21OSErrorErrors related to system operations, encompasses the OS-related errors.
22SyntaxErrorTriggered by parser encountering a syntax error.
23IndentationErrorA subclass of SyntaxError, triggered by incorrect indentation.
24SystemErrorRaised when the interpreter detects an internal error.
25SystemExitRaised when sys.exit() is called.
26TypeErrorRaised when an operation or function is applied to an object of inappropriate type.
27ValueErrorRaised when a function receives an argument of correct type but inappropriate value.
28RuntimeErrorAn error that doesn't fall into any other category, typically used for general runtime errors.
29NotImplementedErrorRaised to indicate that an abstract method requires an overridden implementation in a subclass.

Example 1: Handling KeyError

This example demonstrates handling a KeyError, which occurs when a requested key is not found in a dictionary.

Python3
Python3

. . . .

Explanation:

  • The dictionary my_dict only contains keys for 'name' and 'age'.
  • Attempting to access my_dict['address'] raises a KeyError because the 'address' key does not exist.
  • The except KeyError block catches this specific error and prints a message indicating the key is missing.

Example 2: Handling IndexError

This example shows how to handle an IndexError, which is raised when attempting to access an index that is out of the range of a list.

Python3
Python3

. . . .

Explanation:

  • my_list is defined with three elements: indexes 0, 1, and 2.
  • Attempting to access my_list[5] raises an IndexError because there is no element at index 5.
  • The except IndexError block is used to catch the error and inform the user that they have tried to access a non-existent list index.

Understanding and properly handling these exceptions are vital for developing dependable and user-friendly Python applications. This approach ensures your program can gracefully handle errors and provide informative feedback to users, improving both usability and reliability.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next