Understanding try except else Construct in Python

try: and except: is common in programming. But do you know, in python you can use else: construct with try: and except: block.

Here is the general form for using try, except and else:


try:
	# this something() can raise exception.
	something()
except:
	# here you handle if exception is raised.
	handle_exception()
else:
	# no exception was raised
	# something() succeeded so,
	# we are executing something else.
	something_else()

try except else Working

First, statements within try: block are executed. If these statements cause any exception then statements with except: are excuted and statements within else: block are not executed.

Second, statements within try: block are executed. If these statements do not cause any exception then statements with except: are not excuted and statements within else: block are executed.

try except else Python Program


try:
    number1 = float(input('Enter first number: '))
    number2 = float(input('Enter second number: '))
    division = number1/number2
    print('Result is: %f' % division)
except:
    print('Input is wrong!')
else:
    print('Division is successful.')

Output

Run 1:
-----------------
Enter first number: 12
Enter second number: 5
Result is: 2.400000
Division is successful.

Run 2:
-----------------
Enter first number: 33
Enter second number: 0
Input is wrong!

Run 3:
-----------------
Enter first number: 89
Enter second number: d
Input is wrong!