Your experience on this site will be improved by allowing cookies
Exception handling is necessary in an efficient code, as if it is not handled properly, further execution of code stops as soon as any exception occurs. Python provides numerous ways and features to handle these exceptions in Python codes, which makes the code more vulnerable to exceptional situations.
Exception can refer to any situation and condition that does not go with the normal flow of the program and thus have a tendency to halt the execution of the program in between. Some of such exceptions are listed below.
EXCEPTIONS | REASONS |
ZeroDivisionError | When a number is divided by zero. |
NameError | When a global or local name is not found in the code. |
IndentationError | When incorrect indentation is given in the code. |
I/O Error | When any Input or Output operation fails. |
EOF Error | When end of the file is reached and yet operations are being performed. |
Steps for Exception Handling in Python:
There are various ways to use these steps. Some are discussed below;
Syntax 1: Basic way
try:
Code raising exception
except Exception 1:
Code to be executed if this exception occurs
except Exception 2:
Code to be executed if this exception occurs
….
except Exception N:
Code to be executed if this exception occurs
else:
Code to be executed if no exception occurs
Syntax 2: Except with no Exception
try:
Code raising exception
except:
Code to be executed if exception occurs
else:
Code to be executed if no exception occurs
Syntax 3: Multiple Exception in Python
try:
Code raising exception
except Exception 1, Exception 2, Exception 3 ,.., Exception N:
Code to be executed if exception occurs
else:
Code to be executed if no exception occurs
Python Try Finally method of Exception Handling:
Syntax:
try:
Code raising exception
finally:
Code to be executed always whether exception occurs or not
Python Raise Exception:
Python raise Exception statement is used to raise an exception explicitly during the execution of the code, thus forcing an exception to occur, even though there is no such exceptional condition present in the code.
Syntax:
raise Exception_class (statement)
Python Custom Exception:
Python also facilitates the programmers to create their own exceptions. Thes user defined exceptions are often called as Python Custom Exception.
0 comments