0
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.

7
  • 2
    w3schools.com/python/python_try_except.asp Commented Jul 13, 2020 at 17:34
  • 3
    What have you read on the topic and what is not clear about it? Commented Jul 13, 2020 at 17:35
  • 1
    Google ‘exception handling in python’. It is rather different to an if else. Note that the code in finally always runs, which can be useful. Commented Jul 13, 2020 at 17:36
  • The vendor seems to provide information on the subject: docs.python.org/3/tutorial/errors.html Commented Jul 13, 2020 at 17:37
  • 1
    Basically, they are there to catch errors. If you have some code that might result in an error, you put it in a try block and if it creates an error, the code in except gets executed instead of your program just stopping. Commented Jul 13, 2020 at 17:37

2 Answers 2

2

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!

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.