Net-informations.com
SiteMap  | About    

Python Exception Handling

What is an exception?

An Exception is an unwanted event that interrupts the normal flow of the program. This could be a programming error attempting to divide by zero , attempting to invoke a method on an object that does not define the method, or passing an invalid argument to a method. When an exception occurs program execution gets terminated. In such cases we get a system generated error message .

Why an exception occurs?

There can be several reasons that can cause a program to throw exception . For example, when we try to read a file or get input from a user, there is a chance that something unexpected will happen – the file may have been moved or deleted, and the user may enter data which is not in the right format.

Python Exception Handling

The good thing about exceptions is that they can be handled in Python . By handling the exceptions we can provide a meaningful message to the user about the issue rather than a system generated message, which may not be understandable to a user. All the runtime errors that we have encountered are called exceptions in Python. Python uses them to indicate that something exceptional has occurred, and the program cannot continue unless it is handled.

All exceptions are subclasses of the Exception class. A try-except statement can be used to wrap entire programs or just particular portions of code to trap and identify errors. If an error occurs within the try statement, an exception is raised, and the code under the except statement is executed. For example, it is not possible to divide by zero . If we try to do this, a ZeroDivisionError is raised and the script is interrupted.

example

The following error message will get when the above code is executed.

A try-except statement can be used to wrap entire programs or just particular portions of code to trap and identify errors. Place the code where we expect an exception after try keyword. The except keyword catches the exception if it is raised. The exception type is specified after the except keyword.

example

output

try...finally

A finally clause is always executed before leaving the try statement , whether an exception has occurred or not. Suppose you are reading a file in your Python program. How do you ensure that the file object is closed properly whether or not an exception was raised? This can be done using the finally block . The finally clause can use to make sure files or resources are closed or released regardless of whether an exception occurs, even if you don't catch the exception.

example

This type of construct makes sure the file is closed even if an exception occurs.









net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.