Md. Nazmul Hassan
Md. Nazmul Hassan

Reputation: 21

When do we need to use " try, except" in python? Is it similar to "if, else"?

try: 
  print(x)
except:
  print("Done!!")

Why do we need to use, try and except.

Can someone explain try and except method? Could you answer with an example and explanation.

Upvotes: 0

Views: 2910

Answers (2)

TruVortex_07
TruVortex_07

Reputation: 280

The try and except blocks are used to catch and handle exceptions. The program will first run the try statement "normally". If there are any exceptions that trigger in the try statement, the except statement will trigger. For example,

try:
    print(str) #Here, str isn't defined and you will get an exception which triggers the except statement
except NameError: #Here, you specify which exception you think might happen
    #Do something

You can have as many exception blocks as you want! Also note that if you catch an exception the other ones will not trigger. Also note that an exception block with no arguments will catch all exceptions.

The finally block can be added on and triggers even if there was an exception or not. This can be helpful for closing and cleaning objects. Another example,

try:
    #stuff
except:
    #stuff if exception
finally:
    #do stuff even if there is or is not an exception

I should also mention the pass function. You should use it if you want to ignore exceptions. Example,

try:
    #stuff
except:
    pass #i don't want to do anything

Hope I helped!

Upvotes: 2

BoxifyMC
BoxifyMC

Reputation: 63

Try and except are used when you want to catch an error. Basically, it would first run the code under try. If it catches an error, it moves on and runs the code under except. Like this:

try:
    print(x)
except:
    print('Could not find variable x.')

It will run what is under try, and if the code runs successfully it will skip the except part and continue running your program. In our case, if x is defined then it will run successfully, however if it not it will catch the error and go to except.

Upvotes: 0

Related Questions