1try:
2 # Dangerous stuff
3except ValueError:
4 # If you use try, at least 1 except block is mandatory!
5 # Handle it somehow / ignore
6except (BadThingError, HorrbileThingError) as e:
7 # Hande it differently
8except:
9 # This will catch every exception.
10else:
11 # Else block is not mandatory.
12 # Dangerous stuff ended with no exception
13finally:
14 # Finally block is not mandatory.
15 # This will ALWAYS happen after the above blocks.
1>>> def catch():
2... try:
3... asd()
4... except Exception as e:
5... print e.message, e.args
6...
7>>> catch()
8global name 'asd' is not defined ("global name 'asd' is not defined",)
1# taking input from the user
2try:
3 age = int(input("Please enter your age: "))
4 print(age)
5except:
6 print("please enter a number instead! ")
7 print('bye')
8
9
10# if you wanna ask their age until they enter the correct number use While Loop
11while True:
12 try:
13 age = int(input("Please enter your age: "))
14 print(age)
15 except:
16 print("please enter a number instead! ")
17 else:
18 break
19
20
1try:
2 print("I will try to print this line of code")
3except ERROR_NAME:
4 print("I will print this line of code if error ERROR_NAME is encountered")
1>>> def divide(x, y):
2... try:
3... result = x / y
4... except ZeroDivisionError:
5... print("division by zero!")
6... else:
7... print("result is", result)
8... finally:
9... print("executing finally clause")
10...
11>>> divide(2, 1)
12result is 2.0
13executing finally clause
14>>> divide(2, 0)
15division by zero!
16executing finally clause
17>>> divide("2", "1")
18executing finally clause
19Traceback (most recent call last):
20 File "<stdin>", line 1, in <module>
21 File "<stdin>", line 3, in divide
22TypeError: unsupported operand type(s) for /: 'str' and 'str'
23
1try:
2 print(x)
3except SyntaxError:
4 print("There is a SyntaxError in your code")
5except NameError:
6 print("There is a NameError in your code")
7except TypeError:
8 print("There is a TypeError in your code")