Python Exception Handling Using try
Python Exception Handling Using try
1. Python has many built-in exceptions that are raised when your program
encounters an error (something in the program goes wrong).
2. When these exceptions occur, the Python interpreter stops the current
process and passes it to the calling process until it is handled.
randomList = ['a', 0, 2]
1. In the above example, we did not mention any specific exception in the
except clause.
2. This is not a good programming practice as it will catch all exceptions
and handle every case in the same way.
3. We can specify which exceptions an except clause should catch.
4. A try clause can have any number of except clauses to handle different
exceptions, however, only one will be executed in case an exception
occurs.
5. We can use a tuple of values to specify multiple exceptions in an except
clause.
try:
# do something
pass
except ValueError:
# handleValueError exception
pass
except:
# handle all other exceptions
pass
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
Python try with else clause
1. In some situations, you might want to run a certain block of code if the
code block inside try ran without any errors.
2. For these cases, you can use the optional else keyword with the
try statement.
Note: Exceptions in the else clause are not handled by the preceding except
clauses.
try:
num = int(input("Enter a number: "))
assert num % 2 == 0
except:
print("Not an even number!")
else:
reciprocal = 1/num
print(reciprocal)
Python try...finally
try:
f = open("test.txt",encoding = 'utf-8')
# perform file operations
finally:
f.close()
class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass
class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass