-1

I am trying to catch an exception for two boolean (for if and else separately).

this is what I am working on:

from math import *
from decimal import Decimal


def add(self, *args):
    try:
        if all(isinstance(n, int) for n in args):
            print(sum(int(n) for n in args))
        else:
            print(fsum(Decimal(n) for n in args))
    except (NameError, SyntaxError) as e:
        print("Error! {}".format(e))

def main():
    add(a)

if __name__ == '__main__': main()

Both if and else gives me two exceptions NameError and SyntaxError, if I give add(a) its giving me NameError as the exception. But the except is not catching the error.

How should I catch the exception for both of them separately?

Akshay
  • 2,622
  • 1
  • 38
  • 71

2 Answers2

2

From what I understand I think you can try like this.

except NameError as e :
      print "Name error occured"
      print("Error! {}".format(e))
except SyntaxError as f:
      print "Syntax error occurred"
      print("Error! {}".format(f))
d-coder
  • 12,813
  • 4
  • 26
  • 36
1

Ok, person who gave me -1, just to let you know that it was an honest mistake and i am new to python. keeping that aside.

so just got to know that SyntaxError are thrown at compile time which cannot be caught at run time that is what -> [SyntaxError not excepting in Python 3 says

so I figured it and thanks to @thefourtheye

from math import *
from decimal import Decimal


    def add(*args):

        if all(isinstance(n, int) for n in args):
            print(sum(int(n) for n in args))
        else:
            print(fsum(Decimal(n) for n in args))


    def main():
        try:
            add(dfvdv)
        except NameError:
            print("Error!")

    if __name__ == '__main__': main()
Community
  • 1
  • 1
Akshay
  • 2,622
  • 1
  • 38
  • 71