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

Reading Exception Handling

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

Reading Exception Handling

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

9/28/23, 12:36 PM about:blank

Exception Handling in Python


Estimated time needed: 10 Minutes

Objectives
1. Understanding Exceptions
2. Distinguishing Errors from Exceptions
3. Familiarity with Common Python Exceptions
4. Managing Exceptions Effectively

What are exceptions?


Exceptions are alerts when something unexpected happens while running a program. It could be a mistake in the
code or a situation that was not planned for. Python can raise these alerts automatically, but we can also trigger
them on purpose using the raise command. The cool part is that we can prevent our program from crashing by
handling exceptions.

Errors vs. Exceptions


Hold on, what is the difference between errors and exceptions? Well, errors are usually big problems that come
from the computer or the system. They often make the program stop working completely. On the other hand,
exceptions are more like issues we can control. They happen because of something we did in our code and can
usually be fixed, so the program keeps going.

Here is the difference between Errors and exceptions:-

Aspect Errors Exceptions


Origin Errors are typically caused by the Exceptions are usually a result of
environment, hardware, or operating system. problematic code execution within the program.
Nature Errors are often severe and can lead to Exceptions are generally less severe and can
program crashes or abnormal termination. be caught and handled to prevent program
termination.
Handling Errors are not usually caught or handled Exceptions can be caught using try-except
by the program itself. blocks and dealt with gracefully, allowing
the program to continue execution.
Examples Examples include “SyntaxError” due to Examples include “ZeroDivisionError” when
incorrect syntax or “NameError” when a dividing by zero, or “FileNotFoundError” when

about:blank 1/4
9/28/23, 12:36 PM about:blank

Aspect Errors Exceptions


variable is not defined. attempting to open a non-existent file.
Categorization Errors are not classified into categories. Exceptions are categorized into various
classes, such as “ArithmeticError,” “IOError,”
“ValueError,” etc., based on their nature.

Common Exceptions in Python


Here are a few examples of exceptions we often run into and can handle using this tool:

ZeroDivisionError: This error arises when an attempt is made to divide a number by zero. Division by
zero is undefined in mathematics, causing an arithmetic error. For instance:
For example:
result = 10 / 0
# Raises ZeroDivisionError

ValueError: This error occurs when an inappropriate value is used within the code. An example of this is
when trying to convert a non-numeric string to an integer:
For example:
num = int("abc")
# Raises ValueError

FileNotFoundError: This exception is encountered when an attempt is made to access a file that does not
exist.
For example:
with open("nonexistent_file.txt", "r") as file:
content = file.read() # Raises FileNotFoundError

IndexError: An IndexError occurs when an index is used to access an element in a list that is outside the
valid index range.
For example:
my_list = [1, 2, 3]
value = my_list[1] # No IndexError, within range
missing = my_list[5] # Raises IndexError

KeyError: The KeyError arises when an attempt is made to access a non-existent key in a dictionary.
For example:
my_dict = {"name": "Alice", "age": 30}
value = my_dict.get("city") # No KeyError, using .get() method
missing = my_dict["city"] # Raises KeyError

TypeError: The TypeError occurs when an object is used in an incompatible manner. An example
includes trying to concatenate a string and an integer:
For example:
result = "hello" + 5 # Raises TypeError

AttributeError: An AttributeError occurs when an attribute or method is accessed on an object that


doesn’t possess that specific attribute or method. For instance:
For example:
text = "example"
length = len(text) # No AttributeError, correct method usage
missing = text.some_method() # Raises AttributeError

ImportError: This error is encountered when an attempt is made to import a module that is unavailable.
For example: import non_existent_module

about:blank 2/4
9/28/23, 12:36 PM about:blank

Note: Please remember, the exceptions you will encounter are not limited to just these. There
are many more in Python. However, there is no need to worry. By using the technique
provided below and following the correct syntax, you will be able to handle any exceptions
that come your way.

Handling Exceptions:
Python has a handy tool called try and except that helps us manage exceptions.

Try and Except : You can use the try and except blocks to prevent your program from crashing due to
exceptions.

Here is how they work:

1. The code that may result in an exception is contained in the try block.
2. If an exception occurs, the code directly jumps to except block.
3. In the except block, you can define how to handle the exception gracefully, like displaying an error
message or taking alternative actions.
4. After the except block, the program continues executing the remaining code.

Example: Attempting to divide by zero

1. 1
2. 2
3. 3
4. 4
5. 5
6. 6
7. 7
8. 8
9. 9
10. 10

1.
2. # using Try- except
3. try:
4. # Attempting to divide 10 by 0
5. result = 10 / 0
6. except ZeroDivisionError:
7. # Handling the ZeroDivisionError and printing an error message
8. print("Error: Cannot divide by zero")
9. # This line will be executed regardless of whether an exception occurred
10. print("outside of try and except block")

Copied!

Next Step
As we finish up this reading, you are ready to move on to the next part where you will practice handling errors.
For better learning, try out different types of data in the lab. This way, you will encounter various errors and
learn how to deal with them effectively. This knowledge will help you write stronger and more reliable code in
the future.

Author(s)
about:blank 3/4
9/28/23, 12:36 PM about:blank

Akansha Yadav

Changelog
Date Version Changed by Change Description
2023-08-11 0.1 Akansha Yadav Initial version created

about:blank 4/4

You might also like