0% found this document useful (0 votes)
2 views

Unit9ErrorsandExceptionsHandling

The document explains error and exception handling in Python, detailing the use of try, except, else, and finally blocks. It defines common types of errors, such as SyntaxError and ValueError, and explains how the raise keyword can be used to throw exceptions. Additionally, it emphasizes that the finally block executes regardless of whether an error occurred, making it useful for resource cleanup.

Uploaded by

Rexzyl Claje
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Unit9ErrorsandExceptionsHandling

The document explains error and exception handling in Python, detailing the use of try, except, else, and finally blocks. It defines common types of errors, such as SyntaxError and ValueError, and explains how the raise keyword can be used to throw exceptions. Additionally, it emphasizes that the finally block executes regardless of whether an error occurred, making it useful for resource cleanup.

Uploaded by

Rexzyl Claje
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Errors and Exceptions

Handling
Unit 9
CCS 1400
Differentiate
try, except,
else, and finally
blocks

Objectives Define the raise


keyword

Create a
program that
handles errors or
exceptions
try and except Basic
Terminology and Syntax
▪ Error
− a problem in a program that stops it from completing its
task

▪ Exception
− a condition that disrupts the normal execution of the
program

▪ Both are types of runtime errors which occur during


program execution
▪ try block
− tests a block of code for errors

▪ except block
− handles the error

▪ else block
− executes code when there is no error

▪ finally block
− executes code, regardless of the result of the try and
except blocks
▪ raise keyword
− used to raise an exception

▪ The kind of error to raise and the message to print can be


defined by the programmer.
Common Types of Errors in Python
Can be
Types of Error Description Example Handled by
Try-Except?
syntax mistake in the code, if x > 10
SyntaxError such as a missing colon or print("x is No
unmatched parentheses greater")

the code is not properly def function():


IndentationError No
indented print("Hello")

a local or global name is not


NameError found, usually occurs when print(y) Yes
using an undefined variable
an operation or function is
TypeError applied to an object of 'hello' + 5 Yes
inappropriate type
a function receives an
ValueError argument of the correct type int('abc') Yes
but an inappropriate value
Common Types of Errors in Python
Can be
Handled
Types of Error Description Example
by Try-
Except?
trying to access an index
my_list = [1, 2, 3];
IndexError that is out of range for a print(my_list[5]) Yes
list, tuple, or string
trying to access a
my_dictio = {'a': 1};
KeyError dictionary key that does print(my_dictio['b']) Yes
not exist
an invalid attribute
'str' object has no attribute
AttributeError reference or assignment 'splitter' Yes
is made
an import statement has
issues, such as importing
ImportError import non_existent_module Yes
a non-existent module
or function
ZeroDivisionError trying to divide by zero 10 / 0 Yes
a file or directory is
FileNotFoundError requested but cannot be open('non_existent_file.txt') Yes
found
▪ Python normally generates an error message if there is an
error or exception

▪ try statement can handle this exception


▪ There can be multiple except blocks
− example: execute a special block of code for a special kind
of error
▪ If no errors were raised, use the else keyword to define the
block of code that will be executed.
Raise an Exception
▪ The programmer can choose to throw an exception if a
condition occurs.

▪ Use the raise keyword to throw or raise an exception

▪ The basic way to raise an exception


▪ The kind of error to raise and the message to display can be
defined by the programmer.
finally Block
▪ If the finally block is specified, it will be executed,
regardless if the try block raises an error or not.
▪ This can be useful to close objects and clean up resources

You might also like