How to Try and Except in Python

1 min

Try and except are perfect when you want to do that might end up in error but don't want the error to stop the program.

The simple case

try:
	something()
except:
	do_this_if_error()

Here we try the something within the something method but if it does fail for any reason, we run the do_this_if_error method if the something method run fails.

Adding specific exception

Sometimes you don't want your program to fail but still want to know which error is being encountered.

To do so you can print the error known as exception like so:

try:
	something()
except Exception as e:
	# This time we print the error
	print(e)
	do_this_if_error()

In this case we do print the error, so that we know what we encounter.

The optimal case

Ideally, a good programmer will want to avoid any loophole in his programm.

You will want to handle every error case individually and correctly.

To do so we can specify the error cases and the code we want to run in any specific case like so:

try:
	something()
except ZeroDivisionError:
	# This time we print the error
	print("There was a division by zero")
except NameError:
	print("The variable doesn't exist")
except TypeError:
	print("There was a cast problem")
else:
	do_this_if_error()
Do something specific for every exception

Conclusion

In the beginning no rush. Keep it simple

It might seem tedious of course.

But it's good practice to handle exception appropriately.