Quantcast
Channel: JS Tricks » Python
Viewing all articles
Browse latest Browse all 25

Python try except: Exceptions Handling

$
0
0

Python provides a very easy yet powerful functionality to handle exceptions. In this lesson we will learn about Python try except for exceptions handling.

Python try except

Exceptions handling is very easy and simple in Python. The code, which harbours the risk of an exception, is embedded in a try block. But whereas in Java exceptions are caught by catch clauses, Python have statements introduced by an “except” keyword in Python. It is possible to “create custom-made” exceptions: With the raise statement it’s possible to force a specified exception to occur.

Syntax

A simple Python try except block will look like this:

try:
   // Code for normal operations
   a = 13
   print a
except:
   // Code if any exception occur
   print "Exception occurred"

There is also an else statement available which you can use after try-except block. If no exception is thrown then else statement is executed. The else must come after the except statement.

Here is an example of the else statement:

try:
    i = 1 / 0
except:
    print("Error")
else:
    print("OK")

In python there is another statement available, it is called finally statement. This clause is always executed, even if an error is raised. We can use “finally” statements as a way to clean up, or to ensure the completion of tasks.

Here is an example of the finally statement:

try:
    # An error occurs.
    x = 1 / 0
except:
    # Except clause
    print("Error encountered")
finally:
    # Finally clause:
    print("Finally clause reached")

Hope this Exception handling tutorial was helpful.

The post Python try except: Exceptions Handling appeared first on JS Tricks.


Viewing all articles
Browse latest Browse all 25

Latest Images

Trending Articles





Latest Images