1

Any idea how we can write multiple except on same line as code to be executed for both exceptions is same.

I tried logical OR but it did not work. My code works as expected if I write both exception separately.

    except FileNotFoundError:
        with open("./file.json", "w") as f:
        json.dump(new_data, f, indent=4)

    except ValueError:
        with open("./file.json", "w") as f:
        json.dump(new_data, f, indent=4)
Woodford
  • 3,746
  • 1
  • 15
  • 29

2 Answers2

4

Put the exception inside brackets (relevant documentation):

try:
    1 / 0
except (RuntimeError, ZeroDivisionError) as err:
    print("Exception!", err)

Prints:

Exception! division by zero
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • It worked. Actually I tried this before posting this question but without () round bracket. Did not knew that except requires tuple for multiple exception in line. – navalega0109 Aug 19 '23 at 05:22
1

An except clause can take multiple exceptions as a parenthesized tuple, for example

except (FileNotFoundError,ValueError ) as error:
    pass
vegan_meat
  • 878
  • 4
  • 10
  • It worked. Actually I tried this before posting this question but without () round bracket. Did not knew that except requires tuple for multiple exception in line. – navalega0109 Aug 19 '23 at 05:23