Python – Exception Handling

There are at least two distinguishable kinds of errors: syntax errors and exceptions.

Errors

Parsing errors are the most common errors that you will see when writing Python. The parser repeats the offending line and an arrow points to the earliest error that was detected. Additionally, the line number and file name for where to look if the code came from the script.

Exceptions

Errors detected during execution are called exceptions and not unconditionally fatal. Most exceptions are not handled by the program but the results will be shown. The last line of the error message will indicate what happened. There are three exception types: ZeroDivision Error, NameError, and TypeError. Standard exceptions are built-in identifiers and not keywords.

Handling Exceptions

It is possible to write programs that handle specific exceptions. See the below example:

While True:

try:

x = int(input(“Please enter a number: “))

break

except ValueError:

print(“That number is no longer valid. Please try again…”)

The try statement first executes the statements between the try and except clause. If no exception occurs the exception clause is skipped and the code in the try clause finishes executing. If an exception is occurs during execution the rest of the clause is skipped and then if the type matches the exception named after the exception keyword then the except clause is executed. After the execution continues after the try statement.

If the exception doesn’t match it will through an unhandled exception and stop the program. The try….except statement can also have an else clause which if present must follow all except statements.

Raising Exceptions

The raise action allows programmers to force specific actions.

For example:

raise NameError(‘Hi There’)


Traceback (most recent call last):

file “<stdin>”, line 1, in <module

NameError: HiThere


User Defined Exceptions

Programmers may create their own exception classes and should typically derive from the Exception class either directly or indirectly. They are often kept simple and offer a number of attributes to allow errors to be handled by exception.

The finally clause is always executed before leaving the try statement. When an exception has occurred in the try clause that is not handled by the exception it is re-raised after the finally clause has been executed.

 

**This article is written for Python 3.6

<< Defining Functions

Classes >>

%d bloggers like this: