In Python, all exceptions must be instances of a class that derives
from BaseException
.
In a try statement with an except clause that mentions a particular
class, that clause also handles any exception classes derived from
that class (but not exception classes from which it is derived).
Two exception classes that are not related via subclassing are never
equivalent, even if they have the same name.
Python’s exception handling infrastructure allows programmers to
cleanly separate the code that implements the focused algorithm from
the code that deals with exceptional situations that the algorithm may
face.
This approach is more modular and encourages the development of
code that is cleaner and easier to maintain and debug.
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StopAsyncIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
| +-- ModuleNotFoundError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- OSError
| +-- BlockingIOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
| +-- IsADirectoryError
| +-- NotADirectoryError
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
| +-- RecursionError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- ResourceWarning
The built-in exceptions can be generated by the interpreter or built-in
functions.
Except where mentioned, they have an “associated value” indicating the
detailed cause of the error.
This may be a string or a tuple of several items of information (e.g., an
error code and a string explaining the code).
The associated value is usually passed as arguments to the exception
class’s constructor.
try:
#block of code
except Exception1:
#block of code
except Exception2:
#block of code
#other code
try:
#block of code
except Exception1:
#block of code
else:
#this code executes if no except block is executed
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
# Using Exception with except statement. If we print(Exception) it will return exception class
except Exception:
print("can't divide by zero")
print(Exception)
else:
print("Hi I am else block")
Declaring Multiple Exceptions
try:
#block of code
except (<Exception 1>,<Exception 2>,<Exception 3>,...<Exception n>)
#block of code
else:
#block of code
try:
a=10/0;
except(ArithmeticError, IOError):
print("Arithmetic Exception")
else:
print("Successfully Done")
the try...finally block
try:
# block of code
# this may throw an exception
finally:
# block of code
# this will always be executed
try:
fileptr = open("[Link]","r")
try:
[Link]("Hi I am good")
finally:
[Link]()
print("file closed")
except:
print("Error")
x = 0
while x < 100:
try:
x = int(input("Please enter a small positive integer: "))
print("x =", x)
if x < 5:
a = None
a[3] = 2 # Using None as a populated list!
elif x < 10:
a = [0, 1]
a[2] = 3 # Exceeding the list's bounds
except ValueError:
print("Input cannot be parsed as an integer")
except TypeError
print("Trying to use a None as a valid object")
except IndexError:
print("Straying from the bounds of the list")
print("Program continues")
print("Program finished")