Reputation: 39
So I want to be efficient in making code in python, and I am doing something like this:
try:
#Code A
except:
#Code A
try:
#Code B
except:
#Code B
try:
#Code B
except:
#Code B
But I want to link all of them to one except
block so I can use an else
statement to catch em' all! (Reference intended).
So could I do something like the following?
try:
#Code A
try:
#Code B
except:
#Code C
else:
#Code D
I have tried the code, but to my self findings and limited questions that are 'similar' all I get is: Error: invalid syntax "try:"
. Is there anything I can do about this?
Upvotes: 0
Views: 1148
Reputation: 4440
It is always good practice to have more generic except block for a specific exception type. a single try statement with multiple except block
try:
#put your risky code
# put another risky code
pass
# multiple exception block will help to catch exact exception and can perform
# operation
except KeyError:
pass
except IOError:
pass
except ValueError:
pass
except Exception:
pass
else:
pass
Upvotes: 1
Reputation: 743
No you can't have multiple try block associated with only one except block. but you can have muliple except block releated to only one try block.
every try block need except block if you didn't provide one you will have an exception.
example of mulitple except block releated to one try block :-
try:
# do something
pass
except ValueError:
# handle ValueError exception
pass
except (TypeError, ZeroDivisionError):
# handle multiple exceptions
# TypeError and ZeroDivisionError
pass
except:
# handle all other exceptions
pass
suppose you perform some operation in try block and you encountered a problem then first except block will take the control if it can't handle the exception then the below except block will handle it and so on......
Note: if the first except block can handle the exception the next except block does not execute or will not come in action.
Upvotes: 1
Reputation: 37287
You actually don't need those extra try
s at all. Whenever there's an exception raised inside the try
block, all code starting there until the end of the block is skipped and the control jumps immediately to the matching except
block. And as well, the else
block is executed when the try
block reachs its end normally. This way you don't need multiple try
blocks - just concatenate them into one and you'll achieve your aim.
Upvotes: 4