Python Exception Handling Tutorial, in this tutorial, we will learn what is an error in Python and how python handles the exception. Here, You will also learn the python effect of exception handling, Raise Exception in Python which are helpful for any Python developers. Are you looking for the information of python exception handling tutorial or Are you dreaming to become to certified Pro Python Developer, then stop just dreaming, get your Python certification course from India’s Leading Python training in btm layout.
Why Python Exception Handling? It is mandatory for a developer to encounter errors in the Program file or code file. If Developers minimize those errors, they wouldn't be great? In Python Programming Language, Exception handling methods will help developers to deal with these potential errors. We hope you understand now the use of Exception Handling in Python.
Do you want to know about how python handles the exception and python effect of exception handling, then just follow the below-mentioned python exception handling tutorial for Beginners from Prwatech and take advanced Python training like a Pro from today itself under 10+ years of hands-on experienced Professionals.
What is an Error in Python?
Exceptions are nothing but errors generated at the time of running code. When an error or exception occurs as we call it, Python will normally stop and through an error message. Exceptions are raised by Python itself or manually from within a program.
Python Effect of Exception Handling
Exceptions are the cause of change in the control flow of a program. When there are exceptions to be handled the default action is immediate termination of the program.
How Python handles the Exception?
It helps in Simplify coding
It provides a uniform approach to handling errors across application code
Due to this robustness is increased.
Python provides the runtime errors through exception handling method with ‘try-except’. Some standard exceptions, mostly observed, are IndexError, ImportError, zero division error, a type error, etc.
In the case of all the exceptions in python, an exception is the base class.
Exception Handling Example
Here we will try to access the array element whose index is out of range and will handle the respective exception.
test= [1, 2,4,8]
print("First element = %d"%(a))
# Only 4 elements are there so at this line it will give an error
print("Fifth element = %d" %(a))
print ("Error occurred")
First element = 1
‘try statement’ can contain more than one except clause, to stipulate handlers for different exceptions. We have to note that only one handler will be executed mostly.
Multiple Exception Handling Example
Here we will try to handle multiple errors with one except statement
vari = 5
if vari< 5 :
# It will generate Zero Division Error for vari=5
cal = vari*2/(vari-5)
# It will generate NameError if vari>= 5
print ("value of cal = ", cal)
# Here round brackets () are necessary for multiple exceptions
print ("\nError Handled")
If the value of vari is changed to greater than or equal to 5, we will get a Name error due to access of variable cal. In that case
Value of cal =
The ‘else’ statement
In python, the else clause on the try-except block can be used which must be present after all the ‘except clauses’. Only when the ‘try clause’ does not raise an exception, the code enters the else block.
Now let’s see the example of the else clause showing exception handling case.
print ('Your age in days is more than',365*int(years))
print('You did not enter an age in integer')
print(age, ‘successfully converted into days')
print('Input test complete')
# If run the above code and put input in integer value like 20 we get the output as:
Your age in days is more than 7300
20 successfully converted into days
Input test complete
# If we put age in form of other than integer like 20.5 etc.then we get:
You did not enter an age in integer
Input test complete
Note: Here ‘else:‘ defines a block that is executed if no exceptions are raised and statement in a block of ‘finally:’ always gets executed.
Raise Exception in Python
The ‘raise’ statement
The raise statement initiates a named exception, which is to have occurred or not. It also permits the programmer to force a specific exception to occur.
raiseNameError("Python code") # It will Raise Error
# To check raising status (raised or not) of exception.
Opening Files and Exceptions
An IOError exception is raised for
Opening a file that not exist
Read or write a file without appropriate access rights
IOError exception attributes include:errno—Error message number, strerror—Error message string, filename—Filename used when the exception was raised.
infile = open('Incorrect filename')
exceptIOError as ioe
print('Unable to open the file')
print('Error number', ioe.args),
print('Filename in error', ioe.filename)
We hope you understand the python exception handling tutorial and Exception Errors Examples concepts. Get success in your career as a Python developer by being a part of the Prwatech, India's leading Python training institute in Bangalore.