Login

Register

Login

Register

✆+91-9916812177 | contact@beingdatum.com

Exception Handling

Basically, an exception is an abnormal condition or error that occurs during the execution of a program. Whenever an exception occurs in a program, the execution of the program halts and the further instruction of the programs are not executed.

We need to handle these exceptions in order to ensure the normal execution of the program.

Some of the common exceptions that occur in Python programs while executing are:

 

  • NameError: This error occurs when a name is not found. 
  • ZeroDivisionError: When a number is divided by zero, ZeroDivisionError occurs.
  • IndentationError: This error occurs due to the wrong indentation.
  • IOError: When Input-Output operation fails, IOError occurs.

 

So, in Python we use the try, catch, except and finally to handle the exceptions.

try-except block

In the Python program, the line of code that may throw exceptions is placed in the try block.

The try block should have except block with it to handle the exception. As an illustration – If any exception occurs in try block then the statements in except block will be executed.

 

 

Example:

 

“else” block

In this case, the else block will be executed if no exception occurs.

Example:

 

“finally” block

If we want a piece of executable code, which we cannot skip under any circumstances, then we need to put this code in the finally block.

Example:

 

Here, in this tutorial, we learned all the basics of Python which are variables, string, numbers, data types, tuples, lists, sets, dictionary, conditional statements, loops, user-defined functions, and exception handling..

SEE ALL Add a note
YOU
Add your Comment
 
© BeingDatum. All rights reserved.
X