×

Html & Html5

The World's best Software Development Study Portal

Python try , except


The try block lets you to test a block of code of errors, whereas except block allows you to handle the error. And then finally with the finally block you can execute the code , regardless of the result of the try - and except blocks. Let’s understand them one-b- one as follows:-


try statement:-

Whenever any error occurs Python normally use to stop and generate an error message but these exceptions we can also handle by the try statement.
Let’s understand it by the following program :-

try:

print(x)

except:

print("An error is there")





Output of this Program


trypy1.png

Here as we can see that the X is not been defined and if try block raise an error than the except block will be executed.



else keyword : -

If there are no errors than with the help of else keyword we can define a block of code to be executed.
Let’s understand it by the following program :-

try:

print("Hi Manish")

except:

print("Nothing is good")

else:

print("Everything is fine")





Output of this Program


trypy2.png

Here that block of code is executed which is in the else part because there is no error.



Finally

Whether try block raises error or not the finally block will be executed . It is independent form the try block .
Let’s make it clear through the following program :-

try:

print(x)

except:

print("Something is wrong ")

finally:

print("Whether something is wrong or not I will execute")





Output of this Program


trypy3.png

As we can see both block of code is executed here.



python training insitute| Best IT Training classes in Gurgaon | python training