Python Exception Handling Learning For Free

In this tutorial, you’ll study Python exception handling, try, catch and at last block.

Program code is developed by humans and thus it’s close to being wrong typically. it should happen that our code consists of errors like semantic error, a programming error, linguistics errors and lots of others. it’s necessary for Python to dam the execution of a program and lift error messages. this can be what’s referred to as exceptions.

Python Exception Handling

An exception is an Associate in the Nursing undesirable event that arises throughout the execution of a program that disrupts the traditional flow of the program’s directions.

To handle these errors or exceptions, we have a tendency to use the technique of Exception Handling.

Exceptions are ordinarily caused because of the subsequent events:

A File that’s to be opened however isn’t found within the memory.

Invalid entry of information by the user.

Example

Traceback (most recent call last): File "xyx.py", line 1, in <module> print a NameError: name 'a' is not defined

This is Associate in Nursing example of Python error. The profit with Python is that it provides the North American nation well details error messages.

In the higher than a program, it tells ME the error line variety and also the error line code. Moreover, it conjointly tells ME if I actually have forgotten something. Like, within the higher than the program I actually have lost to declare variable a and directly printing variable onto the console.

With the assistance of Python exception handling technique, we will avoid abrupt termination of a program and handle interruptions and errors and forestall the program from closing short.

While creating your program code, if you’re thinking that a definite a part of your program code might not work properly, then on execution it should terminate short and your system may crash. to forestall all of this, you will add Associate in Nursing exception block in your code so if miscalculation happens, Python Interpreter can catch that exception and forestall your program from blinking.

Python customary Exceptions

There are some pre-defined or customary exceptions within the Python library. So, you’ll use one amongst them if your desires are sufficed. These exceptions are as follow:

IOError: it’s raised once Associate in Nursing I/O operation fails to execute like when an effort is formed to open a get into browse mode that doesn’t exist.

IndexError: This error is raised once a sequence is indexed with a variety of part that doesn’t exist.

KeyError: This error is raised once a lexicon key’s not found.

NameError: it’s raised once a reputation of Associate in Nursing symbols like a variable or a operate isn’t found.

SyntaxError: it’s raised once a programming error happens.

TypeError: it’s raised once an inbuilt operation or operate is applied to Associate in the Nursing object of an inappropriate data type.

ValueError: It happens once an inbuilt operation or a operate receive Associate in the Nursing argument that has the proper kind however an inappropriate price.

ZeroDivisionError: it’s raised once the second argument of a division or modulo operation is zero.

Python try-except Block

Code

try:
	statement 1
	statement 2
	statement n
except:
	statement 1
	statement 2
	statement n

Example

try:
	var1=float(raw_input("Enter a Number:\n"))
	print("\n")
except:
	print("Erorr Executing")

Output

Enter a Number: 
Justtechreview.com 
Erorr Executing 

The standard thanks to handling exceptions is by as well as a try to except block in your program code. within the strive block, you’ll write a vicinity of code that would most likely raise miscalculation. The except block is then written so if your exception comes true, the management of the program is passed to the except block and you may so forestall program from an abnormal termination.

ere, I actually have declared a variable to require at float price through raw_input() operate. I actually have enclosed this code into strive block so if miscalculation happens I may transfer it into exception block and might then handle the program by giving an error message.

I have entered string price “JustTechReview.com” whereas the interpreter expects ME to enter a floating price, this arises Associate in Nursing exception. On exception, the management is transferred to the except block and also the print statement is dead.

Multiple Exception Block

You can conjointly embody multiple exception blocks with single strive block that helps the Python interpreter to specify specifically what the error is.

Example

try:
	var1=float(raw_input("Enter a Number:\n"))
	print("\n")
except(SyntaxError):
	print("Syntax Error Occured\n")
except(TypeError):
	print("Invalid Datatype")
except(ValueError):
	print("Invalid Value")

Output

Enter a Number: 
Justtechreview.com
Invalid Value 

Here, I actually have entered Associate in Nursing invalid price as “JustTechReview.com” that is wrong because the program expects a floating price and therefore the management is transferred to the right exception block which is ValueError.

Python finally Block

A final block is extremely helpful in Python exception handling. A finally clause invariably gets dead as presently the management completes the strive block. It doesn’t matter whether or not Associate in Nursing exception has occurred or not.

Code

finally():
	statement 1
	statement n

Example

try:
    var1=float(raw_input("Enter a Number:\n"))
    print("\n")
except:
    print("Erorr Executing\n")
finally:
	print("We are in finally block")

Output

Enter a Number: 123 
We are in finally block 
:-/Desktop$ python abc.py 
Enter a Number: 
justtechreview.com
 Erorr Executing 

In the higher than example, the prompt asks the user to enter the Associate in Nursing number. once Associate in Nursing number is entered, it checks sure exception and since the input is correct it directly goes to the finally block.

Again we have a tendency to try and run the constant program and currently enter a wrong input i.e., string. now Associate in Nursing exception has been occurred and currently, the management can move to the exception block and as presently because the exception block execution gets over, the management can move in finally block and so terminate or move to the subsequent sequence of statements whichever happens initial.

If you discover something incorrect or have any doubts concerning higher than Python exception handling tutorial then please comment below.

Leave a Comment