Python Exceptions

Python Exceptions:

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:

  • The suspicious code which can raise an exception is enclosed in the Try block.
  • The next block is of Except statement which specifies the statement to be executed if the corresponding exception occurs.
  • The last block is of Else statement which specifies the statement to be executed in case of no exception.

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:

  • The suspicious code which can raise an exception is enclosed in the Try block.
  • The next block is of Finally statement which specifies the statement to be executed always irrespective of the fact that exceptions occurred or not during the code execution.

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.

 

 

Please follow and like us:
Content Protection by DMCA.com