0% found this document useful (0 votes)
89 views5 pages

Xii Cs Worksheet-exceptions

The document outlines the differences between exceptions and errors in Python, explaining that errors are serious issues requiring programmer intervention, while exceptions can be handled within the program. It details the syntax and usage of exception handling using try, except, else, and finally blocks, along with examples of raising exceptions and common exception types. Additionally, it discusses syntax errors, logical errors, and runtime errors, providing examples and characteristics for each type.

Uploaded by

Mohammed Mishal
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)
89 views5 pages

Xii Cs Worksheet-exceptions

The document outlines the differences between exceptions and errors in Python, explaining that errors are serious issues requiring programmer intervention, while exceptions can be handled within the program. It details the syntax and usage of exception handling using try, except, else, and finally blocks, along with examples of raising exceptions and common exception types. Additionally, it discusses syntax errors, logical errors, and runtime errors, providing examples and characteristics for each type.

Uploaded by

Mohammed Mishal
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
You are on page 1/ 5

BHARATHI VIDHYALAYA SENIOR SECONDARY SCHOOL

WORK SHEET – EXCEPTIONS


CLASS: XII SUBJECT: COMPUTER SCIENCE
Difference Between Exception and Error
Error: Errors are serious issues that a program should not try to handle. They are usually problems in the
code’s logic or configuration and need to be fixed by the programmer. Examples include syntax errors and
memory errors.
Exception: Exceptions are less severe than errors and can be handled by the program. They occur due to
situations like invalid input, missing files or network issues.
Syntax and Usage
Exception handling in Python is done using the try, except, else and finally blocks.
try:
# Code that might raise an exception
except SomeException:
# Code to handle the exception
else:
# Code to run if no exception occurs
finally:
# Code to run regardless of whether an exception occurs
try, except, else and finally Blocks
try Block: try block lets us test a block of code for errors. Python will “try” to execute the code in this
block. If an exception occurs, execution will immediately jump to the except block.
except Block: except block enables us to handle the error or exception. If the code inside the try block
throws an error, Python jumps to the except block and executes it. We can handle specific exceptions or use a
general except to catch all exceptions.
else Block: else block is optional and if included, must follow all except blocks. The else block runs only if
no exceptions are raised in the try block. This is useful for code that should execute if the try block succeeds.
finally Block: finally block always runs, regardless of whether an exception occurred or not. It is typically
used for cleanup operations (closing files, releasing resources).
Example:
try:
n=0
res = 100 / n
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Enter a valid number!")
else:
print("Result is", res)
finally:
print("Execution complete.")
Raising an Exception :
We use the raise statement when we forcefully want a specific exception to occur. It helps us raise an
exception manually and explicitly signal an error condition. The sole argument in the raise statement shows
the exception we want to raise, which can be an exception instance or exception class.
Syntax :
raise ExceptionType("Optional error message")
In the given syntax,
raise is the keword to raise an exception.
ExceptionType mentions the type of exception to raise.
Optional error message provides additional information regarding the exception.

Example
def check_age(age):
if age < 18:
raise ValueError("Age must be 18 or above.")
else:
print("You are allowed to proceed.")
try:
user_age = int(input("Enter your age: "))
check_age(user_age)
except ValueError as e:
print(f"Error: {e}")

Exception Name Description Example


Exception It is the base class for all
exceptions as they inherit from
this class.

ImportError It is raised when an import from utils import my_function


statement fails to find the module
being imported. Importerror: No module named 'utils'

ZeroDivisionError It is raised when we take zero as a result = 5 / 0


divisor for division or modulo
operation. ZeroDivisionError: division by zero

ValueError It occurs when a function or num = int("forty-two")


operation gets an argument of
valid type but with invalid values. ValueError: invalid literal for int() with base 10:
'forty-two'

IndexError It occurs when we try to access an numbers = [10, 20, 30]


index that doesn't exist in a numbers[4]
sequence.
IndexError: list index out of range

ModuleNotFoundError It is the subclass of ImportError import arrow


and is raised when a module can’t
be found. ModuleNotFoundError: No module named
'arrow'

AssertionError It occurs when an assert statement x = 1


fails. y=0
assert y != 0, "Invalid Operation" # denominator
can't be 0
print(x / y)
AssertionError: Invalid Operation

IndentationError It is the base class for all if 5 > 2:


indentation-related errors and is print("Five is greater than two!")
raised in case of an improper
indentation. IndentationError: expected an indented block

EOFError It is raised when the input() with open('example.txt', 'r') as file:


function reaches the end of the while True:
file. It occurs when there is no line = file.readline()
input from the input() function.
EOFError: EOF when reading a line

FloatingPointError It is raised when a floating-point


operation fails.

FileNotFoundError It is the subclass of OSError and is with open('file_does_not_exist.txt', 'r') as file:


raised when a file or directory
can’t be found. FileNotFoundError: [Errno 2] No such file or
directory: 'file_does_not_exist.txt'

KeyError It occurs when we make an my_dict = {'name': 'John', 'age': 25}


attempt to access a dictionary key print(my_dict['location'])
that doesn’t exist.
KeyError: 'location'

AttributeError It occurs due to failure of attribute my_list = [1, 2, 3]


reference or assignment. print(my_list.lower())

AttributeError: 'list' object has no attribute 'lower'

TypeError It is an exception that occurs when print("hello" / 3)


a specific operation is applied to
an object of an invalid data type. TypeError: unsupported operand type(s) for /:
'str' and 'int'

NameError It is raised when an identifier is print(name)


not present in the local or global
namespace. NameError: name 'name' is not defined

IOError It occurs when an I/O operation with open("hello.py", "r") as f:


fails. content = f.read()
IOError: [Errno 2] No such file or directory:
'hello.py'
SyntaxError A syntax error in Python (or any programming language) is an error that occurs when the
code does not follow the syntax rules of the language. Syntax errors are detected by the
interpreter or compiler at the time of parsing the code, and they prevent the code from being
executed.
These errors occur because the written code does not conform to the grammatical rules of
Python, making it impossible for the interpreter to understand and execute the commands.
Common Causes of Syntax Errors
Following are the common causes of syntax errors −
 Missing colons (:) after control flow statements (e.g., if, for, while) − Colons are
used to define the beginning of an indented block, such as in functions, loops, and
conditionals.
if True
print("This will cause a syntax error")
 Incorrect indentation − Python uses indentation to define the structure of code
blocks. Incorrect indentation can lead to syntax errors.
print("This will cause a syntax error")
 Misspelled keywords or incorrect use of keywords.
prnt("Hello, World!")
 Unmatched parentheses, brackets, or braces − Python requires that all opening
parentheses (, square brackets [, and curly braces { have corresponding closing
characters ), ], and }.

LogicalError Python Logical Errors (Exception)


A logical error in Python, or in any programming language, is a type of bug that occurs when
a program runs without crashing but produces incorrect or unintended results. Logical errors
are mistakes in the program’s logic that lead to incorrect behaviour or output, despite the
syntax being correct.
Characteristics of Logical Errors
 No Syntax Error: The code runs successfully without any syntax errors.
 Unexpected Output: The program produces output that is different from what is
expected.
 Difficult to Detect: Logical errors can be subtle and are often harder to identify and
fix compared to syntax errors because the program appears to run correctly.
 Varied Causes: They can arise from incorrect assumptions, faulty logic, improper
use of operators, or incorrect sequence of instructions.
Example of a Logical Error
Consider a simple example where we want to compute the average of a list of numbers:
numbers = [10, 20, 30, 40, 50]
total = 0
for number in numbers:
total += number
average = total / len(numbers) - 1
print("The average is:", average)

Expected Output: The average of the numbers [10, 20, 30, 40, 50] should be 30.
Actual Output: The program will output The average is: 29.0.
RuntimeError A runtime error in a program is one that occurs after the program has been successfully
compiled.
The Python interpreter will run a program if it is syntactically correct (free of syntax errors).
However, if the program encounters a runtime error - a problem that was not detected when
the program was parsed and is only revealed when a specific line is executed - it may exit
unexpectedly during execution. When a program crashes due to a runtime error, we say it has
crashed
Some examples of Python Runtime errors :
 division by zero
 performing an operation on incompatible types
 using an identifier that has not been defined
 accessing a list element, dictionary value, or object attribute which doesn’t exist
 trying to access a file that doesn’t exist

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy