Search code examples
pythonexceptiontry-except

Error using exception handling in python


I just started learning python, while using the try command in exception handling, I got an syntax error

Here is my code,

def divide(a,b):
    {
        print(a," hello world", b)
        try:
            return a/b
        except:
            print("It is meaningless")
    }
print(divide(1,2))

Here is my output,

PS D:\python> python firstprog.py
  File "firstprog.py", line 4
    try:
      ^
SyntaxError: invalid syntax

Can you help me?


Solution

  • First remove your curly braces, curly braces in python are used for dictionaries/sets shorthand declaration.

    like:

    def divide(a,b):
        print(a," hello world", b)
        try:
            return a/b
        except:
            print("It is meaningless")
    
    print(divide(1,2))
    

    because with curly braces and a colon python is thinking it is some sort of dictionary and throwing an error near try.