Python Exception Handling


Exception Handling

Exceptions occur during execution of a block when errors are detected and interrupt the normal execution of a code block.
Python handle exceptions using the statement try…except, similar to the try…catch in Java.

Examples

Exception Handling using try except ValueError

>>> while True:
	try:
	  v = input("Enter an number value: ")
	  v = int(v)
		break
	except ValueError:
		print("No number value")

		
Enter an number value: test
No number value
Enter an number value: 3
>>> 

Exception Handling using finally

>>> b = 7
>>> while True:
	try:
		a = int(input("My number: "))
		break
	except ValueError:
		print("No number!")
		break
	finally:
		print("Default number: ", b)

		
My number: abc
No number!
Default number:  7
>>>