KEMBAR78
Exception Notes, Homework | PDF | Computer Program | Programming
0% found this document useful (0 votes)
33 views12 pages

Exception Notes, Homework

The document provides an overview of exception handling in programming, detailing various types of errors such as compile-time, run-time, logical, syntax, and semantic errors. It explains the concept of exceptions, how to handle them using try-except blocks, and the importance of the finally block for executing code regardless of exceptions. Additionally, it outlines common built-in exceptions in Python, their causes, and the benefits and drawbacks of exception handling.

Uploaded by

guhankasi.j
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)
33 views12 pages

Exception Notes, Homework

The document provides an overview of exception handling in programming, detailing various types of errors such as compile-time, run-time, logical, syntax, and semantic errors. It explains the concept of exceptions, how to handle them using try-except blocks, and the importance of the finally block for executing code regardless of exceptions. Additionally, it outlines common built-in exceptions in Python, their causes, and the benefits and drawbacks of exception handling.

Uploaded by

guhankasi.j
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/ 12

EXCEPTION HANDLING

Errors
Errors in a program can be categorized into following types:

1. Compile Time Error: Errors that occur during the compilation of the program.

2. Run Time Error: Errors that occur while the program is running. Some of the example of run
time error are:

•Division by Zero
•Using of undefined variable
•Trying to access a non existing file
3. Logical Error: Errors in the program’s logic, which do not produce errors but lead to
incorrect results. Some of the example of logical error are:

•Giving wrong operator precedence


•using wrong variable name for calculation

4. Syntax Errors: Mistakes in writing code that prevent the program from running. Some of the
example of syntax error are:

•Incorrect Indentation
•Misspelled a keyword
•leaving out a symbol such as colon (:), parentheses [{()}] or comma (,).
5. Semantics Errors: Logic errors that produce unintended results.

Exception
– An exception is a type of error that occurs during program execution.
– Python generates an exception whenever an error is encountered.
– Exceptions can be handled to prevent the program from crashing.
Error vs. Exception
– Error: Any mistake or issue in the code.
– Exception: An unexpected situation or error during program execution.

Exception Handling

handling exceptions using try-except


finally blocks
try:
#SomeCode....which may have runtime error
except:
#optional block
#Handling of exception (if required)
else:
#execute if no exception
finally:
#Somecode.....(always executed)

(i)Compile-time errors. These are the errors resulting out of violation of programming
language’s grammar rules. All syntax errors are reported during compilation.
(ii) Run-time errors. The errors that occur during runtime because of unexpected situations.
Such errors are handled through exception handling routines of Python.
Syntax Error
These are the errors resulting out of violation of programming language’s grammar rules. All
syntax errors are reported during compilation. Example:
Exception
Exceptions are unexpected events or errors that occur during the execution of a program, such
as a division by zero or accessing an invalid memory location. These events can lead to
program termination or incorrect results.
“It is an exceptional event that occurs during runtime and causes normal program flow to be
disrupted.”

Exception Handling using. try and except Block:


The try and except block in Python is a way to handle exceptions or errors that may occur
during code execution. This mechanism prevents the program from crashing by allowing it to
continue running even if an error is encountered.
Types of Exception

1. `SyntaxError`: Raised when there is a syntax error in your code.

2. `IndentationError`: Raised when there is an indentation error in your code, such as


mismatched indentation levels.

3. `NameError`: Raised when a local or global name is not found.

4. `TypeError`: Raised when an operation or function is applied to an object of inappropriate


type.

5. `ValueError`: Raised when an operation or function receives an argument of the correct type
but an inappropriate value.

6. `KeyError`: Raised when a dictionary is accessed with a key that doesn’t exist.

7. `IndexError`: Raised when trying to access an element at an invalid index in a sequence (e.g.,
list, tuple).

8. `FileNotFoundError`: Raised when trying to open or manipulate a file that does not exist.

9. `IOError`: Raised for I/O-related errors, such as when reading or writing to a file fails.

10. `ZeroDivisionError`: Raised when attempting to divide by zero.

11. `AttributeError`: Raised when an attribute reference or assignment fails.

12. `ImportError`: Raised when an import statement fails to find the module.

13. `TypeError`: Raised when an incorrect type is passed as an argument to a function or


method.

14. `AssertionError`: Raised when an `assert` statement fails.


15. `KeyboardInterrupt`: Raised when the user interrupts the program (e.g., by pressing
Ctrl+C).

16. `EOFError`: Raised when an input operation reaches the end of the file.

17. `ArithmeticError`: A base class for numeric errors, including `ZeroDivisionError` and
`OverflowError`.

18. `FileExistsError`: Raised when trying to create a file or directory that already exists.

19. `FileNotFoundError`: Raised when trying to access a file or directory that does not exist.

20. `PermissionError`: Raised when trying to perform an operation without the necessary
permissions.

Handling Multiple Errors

Execution Order:
The <try suite> is executed first ; if, during the course of executing the <try suite>, an
exception is raised that is not handled otherwise, and the <except suite> is executed, with
<name> bound to the exception, if found ; if no matching except suite is found then unnamed
except suite is executed.

finally Block
The `finally` Block
– The `finally` block contains code that must execute, whether or not an exception was raised
in the `try` block.
– It ensures that certain actions are taken regardless of the outcome.

In Python, the finally block is an essential part of exception handling, working alongside the
try and except blocks. It allows you to define code that will execute regardless of whether an
exception is raised or not. This can be particularly useful for tasks such as closing files,
releasing resources, or performing cleanup operations to ensure that your program remains in
a consistent state.

Raising/Forcing an Exception
You can raise exceptions manually using the `raise` keyword.
Syntax: `raise <exception>(<message>)` (The exception should be a pre-defined built-in
exception.)

Benefits of Exception Handling


– Exception handling separates error-handling code from normal code.It enhances code
readability and clarity.

– It promotes consistent error-handling practices.

– It leads to clear, robust, and fault-tolerant programs.

The finally block is a part of the try-except block in Python that contains the code that is
executed regardless of whether an exception is raised or not. The syntax of the try-except-
finally block is as follows:

the try block contains the code that may raise an exception. If an exception occurs, the control
is transferred to the corresponding except block, which contains the code to handle the
exception. The finally block contains the code that is executed after the try-except blocks,
regardless of whether an exception occurred or not.
Program using finally and else block

using finally an else block together

In this example, if the user enters an invalid input or attempts to divide by zero, the
corresponding except block handles the exception and prints an error message to the user. If
no exception occurs, the else block is executed and prints the result. Finally, the finally block is
executed and prints a message to indicate the completion of the program execution.
Advantages & Disadvantages of Exception Handling
Advantages of Exception Handling:
• Improved program reliability
• Simplified error handling
• Cleaner code
• Easier debugging
Disadvantages of Exception Handling:
• Performance overhead

• Increased code complexity

• Possible security risks

HOMEWORK – TO BE COMPLETED IN HOMEWORK NOTE


1. Write a Python program that takes two numbers as input from the user and
calculates the quotient of the two numbers. Handle the exceptions that may occur
during the program execution, such as invalid input or division by zero.

2. Write a Python program that takes a list of integers as input from the user and
calculates the average of the numbers. Handle the exceptions that may occur
during the program execution, such as invalid input or division by zero.

3. When are the following built-in exceptions raised? Give examples to support
your answers.
1.ImportError

2.IOError

3.NameError

4.ZeroDivisionError

1. ImportError — It is raised when the requested module definition is not found.


Example :

import module

Output

ModuleNotFoundError: No module named 'module'


2. IOError — It is raised when the file specified in a program statement cannot be opened.

Example :

file = open("file1.txt", "r")

Output

FileNotFoundError: [Errno 2] No such file or directory: 'file1.txt'


3. NameError — It is raised when a local or global variable name is not defined.

Example :

print(var+40)

Output

NameError: name 'var' is not defined.


4. ZeroDivisionError — It is raised when the denominator in a division operation is zero.

Example :

print(50/0)

Output

ZeroDivisionError: division by zero

4. Write output
a)
valid = False
while not valid:
try:
n=int(input("Enter a no:"))
while n%2==0:
print("Bye")
valid = True
except ValueError:
print("Invalid")

b)
Compare the following two Python codes shown below and state the output if the input
entered in each case is -6?

CODE 1
import math
num=int(input("Enter a number of whose factorial you want to find"))
print(math.factorial(num))

CODE 2
num=int(input("Enter a number of whose factorial you want to find"))
print(math.factorial(num))

c)
def getMonth(m):
if m<1 or m>12:
raise ValueError("Invalid")
print(m)
getMonth(6)

d)
An exception is ____________
a) an object
b) a special function
c) a standard module
d) a module

e)Syntax errors are also known as parsing errors. - True/False


f) What exception will be thrown for code
int('65.43')
t[5]
g)
Print(“Good Morning”)
print(“Good night)

5. What is the use of a raise statement? Write a code to accept two numbers and display the
quotient. Appropriate exception should be raised if the user enters the second number
(denominator) as zero (0).

The raise statement is used to throw an exception during the execution of a program.

numerator = float(input("Enter the numerator: "))


denominator = float(input("Enter the denominator: "))
if denominator == 0:
raise ZeroDivisionError("Error: Denominator cannot be zero.")
else:
quotient = numerator / denominator
print("Quotient:", quotient)

Output

Enter the numerator: 25


Enter the denominator: 5
Quotient: 5.0

Enter the numerator: 2


Enter the denominator: 0
Traceback (most recent call last):
File "c:\PythonPlayground\q3.py", line 4, in <module>
raise ZeroDivisionError("Error: Denominator cannot be zero.")
ZeroDivisionError: Error: Denominator cannot be zero.
6. Define the following:
1.Exception Handling

2.Throwing an exception

3.Catching an exception

1.Exception Handling — The process of writing additional code in a program to give


proper messages or instructions to the user upon encountering an exception is known
as exception handling.

2.Throwing an exception — Throwing an exception refers to the process of creating an


exception object and passing it to the runtime system or the appropriate exception
handler.

3.Catching an exception — Catching an exception refers to the process of executing a


suitable handler or block of code specifically designed to handle that particular
exception when it occurs during program execution.

7. Explain catching exceptions using try and except block.

Answer

An exception is said to be caught when a code that is designed to handle a particular exception
is executed. Exceptions, if any, are caught in the try block and handled in the except block.
While writing or debugging a program, a user might doubt an exception to occur in a
particular part of the code. Such suspicious lines of codes are put inside a try block. Every try
block is followed by an except block. The appropriate code to handle each of the possible
exceptions (in the code inside the try block) are written inside the except clause. While
executing the program, if an exception is encountered, further execution of the code inside the
try block is stopped and the control is transferred to the except block.

8. Differentiate type error and value error


The TypeError occurs when an incorrect number of arguments is provided for a function,
while the ValueError occurs when the number of arguments are correct but they contain
inappropriate values. Hence, in the following code TypeError is raised due to providing an
incorrect number of arguments to the math.sqrt() and math.pow() function and it is handled
using except.
import math
Ex:1
try:
result = math.pow(2, 3, 4, 5)
except TypeError:
print("TypeError occurred with math.pow()")
else:
print("Result:", result)

Ex:2
try:
result = math.sqrt(9, 2)
except TypeError:
print("TypeError occurred with math.sqrt()")
else:
print("Result:", result)

9. What is the use of finally clause ?


The statements inside the finally block are always executed, regardless of whether an
exception has occurred in the try block or not.

You might also like