1

Am I being stupid for doing something like this? I feel like I may not fundamentally understand the purpose of try catch blocks.

I have a script that I want to run on auto-pilot on a daemon and what happens sometimes is that it checks to see if some resources in a list are fully allocated or not. If the resource is fully allocated it cannot continue with one thing, but there is other stuff it can do. Because I'm also calling something from an API, sometimes the Exception thrown by the API is very general (just like API_Exception). Is doing multiple try blocks pointless in this situation?

The main issue is that the break doesn't allow me to get out of the loop

for:
    try: 
         stuff()
    except ExceptionA:
         handle()
         break
    except ExceptionB:
         report()
         sys.exit()
    try:
         other_stuff()
    except ExceptionA:
         handle_in_a_different_way()
         break
    except ExceptionC:
         report()
         sys.exit()

other_code_that_should_execute_if_there_is_a_break()

In this case, should I be just combine these two blocks and catch ExceptionA once? ExceptionA might not have easily parseable parameters.

for:
    try:
        stuff()
        other_stuff()
    except ExceptionA:
        if ExceptionA has param
            handle()
        elif ExceptionA has other param
            handle_in_a_different_way()
    except ExceptionB:
        report()
        sys.exit()
    except ExceptionC:
        report()
        sys.exit()
Kshitij Saraogi
  • 6,821
  • 8
  • 41
  • 71
frei
  • 495
  • 3
  • 19

1 Answers1

0

I m not very experienced in exceptions, but I found something in the stack that may be helpfull.

Catch multiple exceptions in one line (except block)

It also depends on which version you are currently using, in python 2 it seems you can use a comma to separate the exceptions, but in python 3 people advise to use 'as'to set them in a variable, then you could verify how to treat them

Community
  • 1
  • 1
Breno Baiardi
  • 99
  • 1
  • 16