Whenever you write larger pieces of code and build more complex applications, exceptions in Python will be commonplace. They can get annoying when one is unable to resolve them.
When do errors occur?
- Giving the wrong input
- A module/library/resource is unreachable
- Exceeding the memory or time
- Any syntax error made by the programmer
Different Exceptions in Python
An exception is defined as a condition in a program that interrupts the flow of the program and stops the execution of the code. Python provides an amazing way to handle these exceptions such that the code runs without any errors and interruptions.
Exceptions can either belong to the in-built errors/exceptions or have custom exceptions. Some of the common in-built exceptions are as follows:
Creating a test exception in Python
Let’s look at some examples of how exceptions look in the Python Interpreter. Let’s look at the output of the code given below.
a = int(input("Enter numerator: ")) b = int(input("Enter denominator: ")) print("a/b results in : ") print(a/b)
The output when the numerator is an integer and the denominator is given as 0 is shown below.
Enter numerator: 2 Enter denominator: 0 a/b results in : Traceback (most recent call last): File "C:/Users/Hp/Desktop/test.py", line 4, in <module> print(a/b) ZeroDivisionError: division by zero
Avoid Exceptions with Try..Except..
In order to avoid the errors coming up and stop the flow of the program, we make use of the try-except statements. The whole code logic is put inside the try block and the except block handles the cases where an exception/error occurs.
The syntax of the same is mentioned below:
try: #block of code except <Name of Exception>: #block of code #Rest of the code
Handling ZeroDivisionError Exceptions in Python
Lets’ look at the code we mentioned earlier showing ZeroDivisionError with the help of try-except block. Look at the code mentioned below.
try: a = int(input("Enter numerator: ")) b = int(input("Enter denominator: ")) print(a/b) except ZeroDivisionError: print("Denominator is zero")
The output of this code for the same inputs as before is shown below.
Enter numerator: 2 Enter denominator: 0 Denominator is zero
Now, you have an introduction to exceptional handling with you and I hope you are clear with the basic concepts of exception handling.
You can try out various exceptions all by yourself. Happy coding! Thank you for reading! 😇