Signup/Sign In
PUBLISHED ON: FEBRUARY 16, 2021

How to Handle Errors in Python?

In this article, we will learn how to handle errors in Python. We will discuss different errors, exceptions with some custom codes as well to better understand the error handling in Python.

What is Error Handling in Python?

Most programs are very large, complex, and written by multiple programmers. This combination of factors almost always leads to different errors in a program. The program terminates its execution as soon as it encounters unhandled errors. So, it is important to check for these errors and correct them for the successful execution of a program. But, there are some errors that cannot be corrected by just looking at the program. Therefore, errors are mainly distinguished into two classes in Python: Syntax Error and Exceptions.

The program terminates when Syntax Error occurs because this error cannot be handled during runtime. The program does not stop its execution when Exceptions occur because these kinds of errors can be handled during runtime. Let us learn about syntax errors and exceptions separately. Further, we will discuss more on exceptions and exception statements that help in handling errors.

Syntax Errors

In Python, Syntax Errors, also known as Parsing Errors, are the most common kind of errors. It occurs when there are some missing characters or the python script uses an invalid python syntax. Look at the below example, the error is detected at the if() statement since a colon (':') is missing at the end.

Exceptions

Exceptions are another class of errors in Python. Even if your python script is not giving any syntax error or it is syntactically correct, it may still cause an error when an attempt is made to execute the program. These are called exceptions or logical errors. Python reports an exception when an exceptional situation/error occurs and it can be handled. These kinds of exceptions avoid program termination because python provides exception statements to handle these errors. We use exceptions in our programs when we think that a block of code can produce an error.

Exceptions in Python

Python has different built-in exceptions that may occur during the program run. When these runtime errors occur, Python creates an exception object and changes the flow of the program. Some of the common errors are ZeroDivisionError, ValueError, TypeError, NameError etc.

Example: Zero Division Error

The following code shows that ZeroDivisionError occurred. It is raised because the second operand of division results in zero. So, this exception occurred and the program terminates.

Example: Name Error

The following code shows that a NameError occurred. It is raised when an identifier is not found in the local or global scope.

Example: Type Error

The following code shows that a TypeError occurred. It is raised when an operation or function is attempted that is invalid for the specified data type.

Why it is Important to Handle Errors?

Error handling is important because it makes it easier for the end-users of your code to use it correctly. It makes your code easier to maintain. It makes it easier to embed input specifications into the code, so you don't have to look up the design when you write and later maintain the code. Another huge reason is security. Certain types of errors, if not handled properly can leave a program and the underlying operating system in a vulnerable state.

Error Handling using Exception Statements in Python

When these exceptions occur, the Python interpreter stops the current process and passes it to the calling process until it is handled. If the exception is not handled, an error message is displayed along with the cause of the error and the program comes to a sudden unexpected halt.

To prevent this situation, we handle exceptions using try, except, and finally clause in Python. These are called Exception Statements. The try block test a block of code for errors. The except block handles the error. The finally block executes the code under all circumstances.

Use try-except block

try statement checks for the error and except statement handles that error. The code within the try clause is executed statement by statement.

This try-except block works as follows:

  1. Python executes the statements inside the try block and checks for the exception.
  2. If no exception occurs, the statements inside except block are skipped and the execution of the try-except block is finished.
  3. If an exception occurs during the execution of the try block, the rest of the statements are skipped. Then if the type matches the exception named after the except statement, this except block is executed.

Example

In this example, try executes the statements inside it and catches error while division. Except block catches the error and prints the error.

try:
	number = 10
	divider = 0
	result = number / divider
except ZeroDivisionError as error:
	print(error)


division by zero

Handling Multiple Exceptions using Multiple except Blocks

A try statement may have more than one except clause, to handle more than one exception but one exception handler will be executed. This gives the user more control over the statements and creates a safety net that you want to execute when a specific exception occurs.

Example

In this example, we handle a ZeroDivisionError and a ValueError. The ValueError occurs when the user doesn’t enter a number and the ZeroDivisionError occurs when the user divides a number by 0. If I provide 0 value to the divider, the code will reach except block and executes the print statement of ZeroDivisionError.

try:
	number = 10
	divider = int(input("Enter the number for division: "))
	result = number / divider
except ZeroDivisionError:
	print("Cannot divide by zero")
except ValueError:
	print("Please enter a number")


0
Enter the number for division: Cannot divide by zero

Use try Statement with else Clause

In some situations, you might want to execute some statements, if the code block inside try ran without any errors. For these cases, you can use the else clause with the try statement. But, exceptions in the else clause are not handled by the preceding except clauses.

Example:

In this example, if we pass an odd number, the try statement works fine and executes the print statement. If we pass an even number, else block works fine and prints the reciprocal. But if we pass 0, the program terminates and results in ZeroDivisonError.

try:
    num = int(input("Enter a number: "))
    assert num % 2 == 0
except:
    print("Not an even number!")
else:
    reciprocal = 1/num
    print("Reciprocal: ", reciprocal)


Enter a number: 0
ZeroDivisionError: division by zero
Enter a number: 1
Not an even number!
Enter a number: 4
Reciprocal: 0.25

Use try statement with finally

In addition to using an except block, you can also use the finally block. The statement inside the finally block will be executed regardless of whether an exception occurs or not. It is intended to define clean-up actions that must be executed under all circumstances. This can sometimes be useful when working with files.

Example

In this example, as finally guarantees its execution, file.close() statement is placed inside the finally block.

try:
    file = open("testfile", "w")
    file.write("Writing to the file")
except IOError:
    print("An IOError occurred while writing to the file")
except Exception as error:
    print(f"An exception occurred {error}")
finally:
    file.close()

Conclusion

In this article, we learned to handle errors using try, except, finally and else clauses in Python. There are different types of built-in exceptions but we discussed only a few of them. But all these exceptions can be handled using try-except block. Python also has user-defined exceptions about which we will discuss later. We saw that it is important to handle errors while writing or building complex codes.



About the author:
An enthusiastic fresher, a patient person who loves to work in diverse fields. I am a creative person and always present the work with utmost perfection.