xxxxxxxxxx
while True:
try:
funds = float(input("Enter amount to transfer: "))
if funds < 0:
raise Exception("Please enter a positive value,")
break
except ValueError:
print("Please enter a numeric value,")
xxxxxxxxxx
try:
# raise a custom exception
raise Exception("A custom exception")
except Exception as err:
print(err)
finally:
print('This execute no matter if an exception occurs or not')
xxxxxxxxxx
def sqrt(x):
if x < 0:
raise <ErrorType>('Exception message') # Exception is default errortype
try:
return x ** 0.5
except <ErrorType>:
print('Exception message')
Here's a list of the names of some common built-in exceptions in Python:
1. BaseException
2. SystemExit
3. KeyboardInterrupt
4. Exception
5. StopIteration
6. GeneratorExit
7. StandardError
8. ArithmeticError
9. FloatingPointError
10. OverflowError
11. ZeroDivisionError
12. AssertionError
13. AttributeError
14. EOFError
15. ImportError
16. ModuleNotFoundError
17. IndexError
18. KeyError
19. NameError
20. UnboundLocalError
21. ValueError
22. UnicodeError
23. UnicodeEncodeError
24. UnicodeDecodeError
25. UnicodeTranslateError
26. EnvironmentError
27. IOError
28. OSError
29. FileNotFoundError
30. PermissionError
31. TypeError
32. AttributeError
33. RuntimeError
34. NotImplementedError
35. RecursionError
Keep in mind that this is not an exhaustive list, but it covers some of the most commonly encountered exceptions in Python.
xxxxxxxxxx
#!/bin/python3
import sys
S = input().strip()
try:
S = int(S)
print(S)
except:
print("Bad String")