© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2022
K. WilsonThe Absolute Beginner's Guide to Python Programminghttps://doi.org/10.1007/978-1-4842-8716-3_8

8. Exception Handling

Kevin Wilson1  
(1)
London, UK
 

An exception is an error that occurs during execution of a program, sometimes called a runtime error. This could be a “file not found” error if you are trying to load a file that doesn’t exist, or a “type error” if you type text into a field when the program is expecting a number.

Exceptions are useful for handling errors encountered with file handling, network access, and data input.

These errors can be handled gracefully using Python’s exception handling procedures.

Types of Exception

Here’s a list of built-in exceptions according to the Python documentation.
Table 8-1

Built in Python Exceptions

Exception

Cause

AssertionError

Raised when assert statement fails

AttributeError

Raised when attribute assignment or reference fails

EOFError

Raised when the input() function hits end-of-file condition

FileNotFoundError

Raised when a file or directory is requested but doesn’t exist. Corresponds to errno ENOENT

FloatingPointError

Raised when a floating point operation fails

GeneratorExit

Raised when a generator's close() method is called

ImportError

Raised when the imported module is not found

IndexError

Raised when index of a sequence is out of range

KeyError

Raised when a key is not found in a dictionary

KeyboardInterrupt

Raised when the user hits interrupt key (Ctrl+C or delete)

MemoryError

Raised when an operation runs out of memory

NameError

Raised when a variable is not found in local or global scope

NotImplementedError

Raised by abstract methods

OSError

Raised when system operation causes system-related error

OverflowError

Raised when result of an arithmetic operation is too large to be represented

ReferenceError

Raised when a weak reference proxy is used to access a garbage collected referent

RuntimeError

Raised when an error does not fall under any other category

StopIteration

Raised by next() function to indicate that there is no further item to be returned by iterator

SyntaxError

Raised by parser when syntax error is encountered

IndentationError

Raised when there is incorrect indentation

TabError

Raised when indentation consists of inconsistent tabs and spaces

SystemError

Raised when interpreter detects internal error

SystemExit

Raised by sys.exit() function

TypeError

Raised when a function or operation is applied to an object of incorrect type

UnboundLocalError

Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable

UnicodeError

Raised when a Unicode-related encoding or decoding error occurs

UnicodeEncodeError

Raised when a Unicode-related error occurs during encoding

UnicodeDecodeError

Raised when a Unicode-related error occurs during decoding

UnicodeTranslateError

Raised when a Unicode-related error occurs during translating

ValueError

Raised when a function gets argument of correct type but improper value

ZeroDivisionError

Raised when second operand of division or modulo operation is zero

Whenever an exception occurs, the interpreter halts the execution of the program and raises an exception error as shown in the table.

You can catch these exceptions using the try and except keywords and provide code to handle the error.

Catching Exceptions

If we run the following code , the Python interpreter will raise a FileNotFoundError exception because there is no file called “file.txt”. This will cause the program to crash.

The python file window shows the set of codes depicting having a File Not Found Error in the window of Python 3.8.1 Shell.

You can catch exceptions using the try and except keywords. Just put your code in the “try” block and your error handling code for each exception in the “exception” block as shown here:
try:
     # Code to execute as normal
except [exception (see table above)]:
     # Code to deal with exception

The try block contains the code to execute. The except block contains the code to handle the error.

Let’s take a look at the program again. We can take our code and place it in the “try’” block. Then add an “except” block to deal with the error. If we look at the error message in the shell, we see this is a FileNotFoundError. We can add this after the “except” keyword.

Now, when we run the program, we get a simple message rather than an ugly error.

The python file window shows the set of codes highlighting the keywords try and except and depicts a File Not Found error in the window of Python.

Use the finally block to perform any clean up. The finally statement runs regardless of whether the try statement produces an exception or not.
try:
     file = open("file.txt", "r") data = file.read()
except FileNotFoundError: print("File not found")
    finally: f.close()

Raising Your Own Exceptions

Use the raise keyword to force a specified exception to occur followed by the type of error using the table in Table 8-1 at the beginning of this chapter.
if number < 0:
     raise ValueError ("Negative numbers only.")

Here in the file raise.py, we’ve raised a ValueError exception .

The python file window shows the set of code depicts a highlighted line that reads raise value error, negative numbers are now allowed.

Summary

  • An exception is an error that occurs during execution of a program, sometimes called a runtime error.

  • You can catch exceptions using the try and except keywords.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.103.202