Exception Handling
class Exception(BaseException)
| Common base class for all non-exit exceptions.
|
| Method resolution order:
| Exception
| BaseException
| object
|
| Built-in subclasses:
| ArithmeticError
| AssertionError
| AttributeError
| BufferError
| ... and 16 other subclasses
| Common base class for all non-exit exceptions.
|
| Method resolution order:
| Exception
| BaseException
| object
|
| Built-in subclasses:
| ArithmeticError
| AssertionError
| AttributeError
| BufferError
| ... and 16 other subclasses
EOFError
ImportError
LookupError
MemoryError
NameError
OSError
ReferenceError
RuntimeError
StopAsyncIteration
StopIteration
SyntaxError
SystemError
TypeError
ValueError
KeyboardInterrupt
SystemExit
.....
Syntax Error - Grammatic Error
Runtime Error - No error in grammar but error during runtime.
All runtime errors are called exceptions.
Example - NameError, AttributeError, ZeroDivException, ValueError,TypeError etc.
object is topmost class which is extended by BaseException class and subsequently by Exception
All these are builtin Exceptions, we can also create exception by extending Exception class.
More about Builtins
Python provides a local() method which has a module named builtins. We can check the classes and methods in builtins as follows
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'x': '_', 'f1': <function f1 at 0x0000012FCB095080>}
>>> locals()['__builtins__']
<module 'builtins' (built-in)> # returns module object
>>> for x in locals()['__builtins__'].__dict__:
... print(locals()['__builtins__'].__dict__[x])
...
builtins
Built-in functions, types, exceptions, and other objects.
This module provides direct access to all 'built-in'
identifiers of Python; for example, builtins.len is
the full name for the built-in function len().
This module is not normally accessed explicitly by most
applications, but can be useful in modules that provide
objects with the same name as a built-in value, but in
which the built-in of that name is also needed.
<class '_frozen_importlib.BuiltinImporter'>
ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>, origin='built-in')
<built-in function __build_class__>
<built-in function __import__>
<built-in function abs>
<built-in function all>
<built-in function any>
<built-in function ascii>
<built-in function bin>
<built-in function breakpoint>
<built-in function callable>
<built-in function chr>
<built-in function compile>
<built-in function delattr>
<built-in function dir>
<built-in function divmod>
<built-in function eval>
<built-in function exec>
<built-in function format>
<built-in function getattr>
<built-in function globals>
<built-in function hasattr>
<built-in function hash>
<built-in function hex>
<built-in function id>
<built-in function input>
<built-in function isinstance>
<built-in function issubclass>
<built-in function iter>
<built-in function aiter>
<built-in function len>
<built-in function locals>
<built-in function max>
<built-in function min>
<built-in function next>
<built-in function anext>
<built-in function oct>
<built-in function ord>
<built-in function pow>
<built-in function print>
<built-in function repr>
<built-in function round>
<built-in function setattr>
<built-in function sorted>
<built-in function sum>
<built-in function vars>
None
Ellipsis
NotImplemented
False
True
<class 'bool'>
<class 'memoryview'>
<class 'bytearray'>
<class 'bytes'>
<class 'classmethod'>
<class 'complex'>
<class 'dict'>
<class 'enumerate'>
<class 'filter'>
<class 'float'>
<class 'frozenset'>
<class 'property'>
<class 'int'>
<class 'list'>
<class 'map'>
<class 'object'>
<class 'range'>
<class 'reversed'>
<class 'set'>
<class 'slice'>
<class 'staticmethod'>
<class 'str'>
<class 'super'>
<class 'tuple'>
<class 'type'>
<class 'zip'>
True
<class 'BaseException'>
<class 'BaseExceptionGroup'>
<class 'Exception'>
<class 'GeneratorExit'>
<class 'KeyboardInterrupt'>
<class 'SystemExit'>
<class 'ArithmeticError'>
<class 'AssertionError'>
<class 'AttributeError'>
<class 'BufferError'>
<class 'EOFError'>
<class 'ImportError'>
<class 'LookupError'>
<class 'MemoryError'>
<class 'NameError'>
<class 'OSError'>
<class 'ReferenceError'>
<class 'RuntimeError'>
<class 'StopAsyncIteration'>
<class 'StopIteration'>
<class 'SyntaxError'>
<class 'SystemError'>
<class 'TypeError'>
<class 'ValueError'>
<class 'Warning'>
<class 'FloatingPointError'>
<class 'OverflowError'>
<class 'ZeroDivisionError'>
<class 'BytesWarning'>
<class 'DeprecationWarning'>
<class 'EncodingWarning'>
<class 'FutureWarning'>
<class 'ImportWarning'>
<class 'PendingDeprecationWarning'>
<class 'ResourceWarning'>
<class 'RuntimeWarning'>
<class 'SyntaxWarning'>
<class 'UnicodeWarning'>
<class 'UserWarning'>
<class 'BlockingIOError'>
<class 'ChildProcessError'>
<class 'ConnectionError'>
<class 'FileExistsError'>
<class 'FileNotFoundError'>
<class 'InterruptedError'>
<class 'IsADirectoryError'>
<class 'NotADirectoryError'>
<class 'PermissionError'>
<class 'ProcessLookupError'>
<class 'TimeoutError'>
<class 'IndentationError'>
<class 'IndexError'>
<class 'KeyError'>
<class 'ModuleNotFoundError'>
<class 'NotImplementedError'>
<class 'RecursionError'>
<class 'UnboundLocalError'>
<class 'UnicodeError'>
<class 'BrokenPipeError'>
<class 'ConnectionAbortedError'>
<class 'ConnectionRefusedError'>
<class 'ConnectionResetError'>
<class 'TabError'>
<class 'UnicodeDecodeError'>
<class 'UnicodeEncodeError'>
<class 'UnicodeTranslateError'>
<class 'ExceptionGroup'>
<class 'OSError'>
<class 'OSError'>
<class 'OSError'>
<built-in function open>
Use quit() or Ctrl-Z plus Return to exit
Use exit() or Ctrl-Z plus Return to exit
Copyright (c) 2001-2023 Python Software Foundation.
In programming, we need to consider exceptional flow apart from normal execution. Example - An ATM should be able to detect balance before actually processing any transaction. It should validate password and user identity. In case any of the condition fails; transaction should not be executed.
By default, python handles exception situation. It gives error and terminates program where error has occurred. This is default behavior behavior of python
Incase programmer wants to implement exception handling python doesn't execute its exception handler; it remains as backup incase user exception is not handled.
Handling exception using if else doesn't work as efficiently as it would be difficult to identify normal and exceptional flow. Hence, to handle exceptional flow, exceptions should be preferred.
Incase using if else block we should be knowing each and every exception condition, this would be quite messy.
Whenever Exception arises it should be handled, and execution of program should not terminate abrubtly.
If we want exception to be handled, it can be done with try keyword.
#Exception Handling
'''
1) Implicit Exception raise(Default and program always terminates)
2) Explicit Exception raise (using raise keyword)
3) Implicit Exception raise - Custom Exception Handler
4) Explict Exception raise - Explict Exception Handler
'''
try:#Code where exception can occur
print("Enter two numbers")
a = int(input())
b = int(input())
c = a/b
print("Result is",c)
#Handle Exception
except (ValueError,ArithmeticError,ZeroDivisionError) as e:
print("Value must be an integer")
try:
d = int(input())
e = int(input())
c = d*e
print("Product is",c)
except Exception:
print("Product error")
we can write any number of exceptions, and if any of the exception occurs then other will not be executed. Whenever exception occurs, then control jump to except clause to see matching exception. If exception is not matched default python exception handler runs, and program terminates. But incase user exception is executed, then program moves as determined by programmer.
Hierarchy - except Exception - except - finally
finally runs in all cases. Irrespective if there is exception or not.
try:#Code where exception can occur
print("Enter two numbers")
a = int(input())
b = int(input())
c = a/b
print("Result is",c)
#Handle Exception
except (ValueError) as e:
print("Value must be an integer")
except Exception:
print('This is Exception')
except: #this should be last in all exception
print("I am general Exception")
finally:
print('This will run always')
Scenario - If we want to execute a piece of code after making sure no exception has occurred, then we can use else block as below.
try:#Code where exception can occur
print("Enter two numbers")
a = int(input())
b = int(input())
c = a/b
print("Result is",c)
#Handle Exception
except (ValueError) as e:
print("Value must be an integer")
except Exception:
print('This is Exception')
except: #this should be last in all exception
print("I am general Exception")
else:
print('Try block code Executed with No exception')
finally:
print('This will run always')
By using exception handling we can make our coding robust - i.e ready for all season and situation.
Custom Exception
We can create a class to represent custom exception by inheriting any exception class and write custom logic.
'''Define own exception - Custom Exception '''
class MyException(Exception):
def __init__(self,msg):
self.msg = msg
def __str__(self):
return self.msg
class Balance:
w = int(input("Enter amount to withdraw"))
bal = 2000
bal = bal - w
try:
if w > bal:
raise MyException('Insufficient balance')
except Exception:
print('Withdrawal amount greater than balance')
else:
print('New Balance is',bal)
Comments
Post a Comment