0% found this document useful (0 votes)
4 views10 pages

Python Exception Handling Syntax Vs Runtime Errors

The document provides an introduction to Python errors, categorizing them into syntax errors and exceptions, and explains their detection and examples. It includes exercises for identifying built-in exceptions, handling errors using try, except, and finally blocks, and emphasizes the importance of anticipating exceptions in programming. Additionally, it contains a formative assessment section with questions and coding practice related to error handling.

Uploaded by

SHIVARTH TIWARI
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views10 pages

Python Exception Handling Syntax Vs Runtime Errors

The document provides an introduction to Python errors, categorizing them into syntax errors and exceptions, and explains their detection and examples. It includes exercises for identifying built-in exceptions, handling errors using try, except, and finally blocks, and emphasizes the importance of anticipating exceptions in programming. Additionally, it contains a formative assessment section with questions and coding practice related to error handling.

Uploaded by

SHIVARTH TIWARI
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Name: ____________________ Date: ____________________

Activity 1: Introduction to Python Errors


According to Section 1.1, when a Python program does not run as expected, it usually falls into one of three
categories of abnormal behavior. List them below:

Three Ways a Program Behaves Abnormally:

1.
2.
3.

Section 1.2 & 1.3: Syntax Errors vs. Exceptions


Use the information from the text to compare these two fundamental types of errors.

Syntax Errors Exceptions (Runtime Errors)

When are they detected? When are they detected?

Description: Description:

Example Scenario: Example Scenario:


Key Terminology

Term Definition (Based on Sections 1.2 - 1.3)

Parsing Errors

Raised

Exception Object

💡 Pro Tip
Remember: A program can be syntactically perfect (no parsing errors) but still crash during execution if it
encounters an Exception, such as trying to divide by zero or opening a file that doesn't exist.

Reflection Question: Why is it important for a programmer to anticipate exceptions while designing a program?
Name: ____________________ Date: ____________________
Built-in Exceptions Reference & Match
Python's standard library provides a collection of built-in exceptions to handle common errors. When one of
these errors occurs, the interpreter 'raises' the exception, providing a standardized way to identify what went
wrong.

Exception Name Explanation

Raised when the denominator in a division operation is


SyntaxError
zero.

Raised when an operator is supplied with a value of an


ValueError
incorrect data type.

Raised when there is an error in the syntax of the Python


IOError
code (parsing error).

Raised when a local or global variable name is not


ZeroDivisionError
defined.

Raised when a method receives an argument with the


IndexError
right type but an inappropriate value.

Raised when the index or subscript in a sequence (like a


NameError
list) is out of range.

Raised when the file specified in a program statement


TypeError
cannot be opened.

Raised when the requested module definition is not


ImportError
found.

Code Analysis: Identifying Exceptions


Analyze the following code snippets. For each, identify which specific built-in exception from the list above
would be raised during execution.

Code Snippet Exception Raised

python

Snippet 1
my_list = [10, 20, 30]
print(my_list[5])
python

Snippet 2
result = "Hello" + 5

python

Snippet 3
x = int("abc")

Pro Tip: Tracebacks


When an exception is raised, Python displays a stack traceback. This text block shows the sequence of
function calls leading to the error, helping you pinpoint exactly where the code failed.
Name: ____________________ Date: ____________________
Coding Practice: Try, Except, and Finally
In Python, exception handling allows a program to deal with unexpected errors without crashing. This is done
using the try , except , and finally blocks. Below is an example based on Program 1-2 from your textbook.

Example: Handling Division by Zero


python
try:
numerator = 50
denom = int(input("Enter the denominator: "))
quotient = numerator / denom
print(quotient)
except ZeroDivisionError:
print("Denominator as ZERO... not allowed")

Part 1: Writing Try...Except Blocks


For each of the following 'unsafe' code scenarios, write a Python code snippet using try and except to
handle the specific exception mentioned. Use the source material's built-in exceptions list for reference.
1. User Input for an Integer: Write a block that attempts to convert a user's input into an integer. If the user
enters a string (like 'abc'), it should catch the ValueError and print a helpful message.

2. Accessing a List Index: Write a block that attempts to print the 10th item in a list called my_list . If the list
is shorter than 10 items, catch the IndexError .
3. Opening a File: Write a block that attempts to open a file named [Link] for reading. If the file does not
exist, catch the IOError .

Part 2: The Finally Clause


The finally clause is used to define clean-up actions that must be executed under all circumstances. Whether
an exception was raised or not, the code inside the finally block will always run. This is often used for closing
files or releasing system resources.

The Exception Handling Flow

Try Block Exception Except Block (if Finally Block


executes occurs? error) (always)

The 'finally' block is the final destination in the execution flow.


Application Task: Rewrite your code from Scenario 1 (the integer input) below. This time, add a finally block
that prints the message: 'Execution Complete' .
Reflection: Why is the finally block useful in professional software development, even if the except block
already handles the error?
Name: ____________________ Date: ____________________
Activity 4: Formative Assessment
Part 1: Theory & Concepts
Select the best answer for each of the following questions based on your reading of the textbook.
1. What is a 'stack traceback' in Python?
A) A list of all variables currently stored in memory.
B) A structured block of text showing the sequence of function calls leading to an exception.
C) A tool used to automatically fix syntax errors in script mode.
D) The process of jumping from a try block to an except block.
2. Which statement is used to forcefully trigger an exception in a program?
A) catch
B) try
C) raise
D) except
3. According to Section 1.2, what is another name for Syntax Errors?
A) Logical Errors
B) Parsing Errors
C) Runtime Exceptions
D) Assertion Errors
4. What happens to the statements in a code block that follow a raise statement?
A) They are executed only if the exception is handled.
B) They are executed normally.
C) They are skipped and not executed.
D) They are moved to the finally block automatically.
5. When an error occurs, the interpreter creates a specific object containing error details. What is this object
called?
A) Error Log
B) Traceback List
C) Exception Object
D) Handler Instance
Part 2: Predict the Output
Read the code snippets below and write exactly what would be printed to the console.
6. Predict the Output:
python
try:
print("Start")
x = 10 / 0
print("End")
except ZeroDivisionError:
print("Error: Division by Zero")

7. Predict the Output:


python
try:
my_list = [1, 2, 3]
print(my_list[1])
except IndexError:
print("Index Out of Range")
finally:
print("Done")
8. Predict the Output:
python
def check_age(age):
assert age >= 18, "Too Young"
return "Access Granted"
print(check_age(15))

Part 3: Short Answer


Provide concise explanations based on Sections 1.5 and 1.6.
9. Explain the purpose of the assert statement as described in Section 1.5.2.

10. Based on the textbook definitions, what is the specific difference between 'raising' an exception and
'catching' an exception?

You might also like