We all know that dividing a number by zero is not mathematically possible. Therefore trying it in your python code can lead to your program crashing.
However, python allows us to look for such errors in our code and catch them, so our program runs even if the error exists.
We do that using the “try” and “except” clauses.
You add the code you want to run inside the try statement. And then when there’s an error(if there’s an exception), you add what you want to do inside the except statement.
Take the below function as an example:
def divide_by(a,b): return a / b
try: ans = divide_by(45, 0)except: print("Something went wrong!")If you run the above code, it will print out what is in the except statement. “Something went wrong!”
However, python allows us to make our except statements more specific. If you want to trap the exception itself, you can add the base class “Exception” right after the except keyword.
The base class “Exception” is used for all exceptions that are written in python. You can gain access to the exception information by using the “as e” after Exception
The “e” variable acts as an alias for the Exception. You can use “e” to print out the exception in the print statement. See below:
try: ans = divide_by(45, 0)except Exception as e: print("Something went wrong!", e)When you run this code, it will print “Something went wrong!, division by zero”
Let’s take this one step further to provide even more specific feedback to the user. In the except statement, replace the base class exception with the actual error that was printed out namely zero division error. See below
try: ans = divide_by(45, 0)except ZeroDivisionError as e: print("Something went wrong!", e)Fortunately, you can chain the except statement by adding another except statement. Let’s say the code doesn’t trigger the zero division error and the first except statement. You could add another except statement that tests for a generic exception.
try: ans = divide_by(45, 0)except ZeroDivisionError as e: print("Something went wrong!", e)except Exception as e: print("Something went wrong!", e)