New programmers are often confused about the topic of exception handling and look for best practices in adopting exception handling into their existing code but without proper knowledge of how exception handling works under the hood it can cause their programs to behave unexpectedly.

In this article I will present a simple use case where using the built-in python exception is insufficient and results in an obscure error message that I will work through and attempt to improve on starting with using the built-in exception initially and then gradually defining our own custom exception to demonstrate a somewhat realistic thinking process as a programmer works through the program

Let’s begin with the example

This program tries to calculate the area of a triangle. If you recall from your secondary school geometry class, a triangle is invalid if the sum of any of its two sides is less than the third side.

Here’s what an implementation of this function looks like

import math

	def triangle_area(a: int, b: int, c: int):
	  p = (a+b+c)/2
	  area = math.sqrt(p * (p-a) * (p-b) * (p-c))
	  return area

#better-programming #exception #python-programming #python

Learn to properly define your own exceptions in python are insufficient
1.50 GEEK