0% found this document useful (0 votes)
80 views8 pages

Ch. 1 Exception Handling New NCERT Syllabus

Chapter 1 discusses exception handling in Python, explaining what errors and exceptions are, including syntax, runtime, and logical errors. It details the importance of exception handling, how to raise and catch exceptions using try, except, else, and finally blocks, and the role of built-in exceptions. The chapter emphasizes the need for proper error management to prevent program crashes and ensure smooth execution.

Uploaded by

tharungowda.g321
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)
80 views8 pages

Ch. 1 Exception Handling New NCERT Syllabus

Chapter 1 discusses exception handling in Python, explaining what errors and exceptions are, including syntax, runtime, and logical errors. It details the importance of exception handling, how to raise and catch exceptions using try, except, else, and finally blocks, and the role of built-in exceptions. The chapter emphasizes the need for proper error management to prevent program crashes and ensure smooth execution.

Uploaded by

tharungowda.g321
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/ 8

Chapter – 1

Exception Handling in Python (New NCERT Syllabus)

1. What happens when errors occur in Python programs?

Sometimes, while executing a Python program:

 The program may not execute at all, or


 It may execute but produce unexpected output or behave abnormally.

2. What are exceptions in Python?

In Python, exceptions are errors that occur automatically during execution. They can also be
forcefully triggered and handled through program code.

3. What are syntax errors, and how does Python handle them?

 Syntax errors (also called parsing errors) occur when Python’s language rules are
violated in the code.
 When a syntax error is encountered, Python stops execution until the error is
corrected.

Handling Syntax Errors

 In Shell Mode: Python displays the name of the error and a brief description of the
issue.

 In Script Mode: A dialog box appears, showing the error name and a short
explanation.

Chethan M B Arehalli | II PUC (New NCERT Syllabus) | Parikrma Junior College | Computer Science
5. What are the types of errors in Python, and how are syntax errors displayed?

Errors in Python may cause the program to stop executing, produce incorrect output, or
behave abnormally.

There are three types of errors:

 Syntax Errors (Parsing Errors)


 Runtime Errors
 Logical Errors

Syntax Errors (SyntaxError)

 Occur when the code violates Python’s syntax rules.


 Must be fixed before the program runs.

How Syntax Errors Are Displayed:

 In Shell Mode: Python displays the error name and a brief description.
 In Script Mode: A dialog box appears showing the error and description.

6. What are exceptions in Python, and why is exception handling important?

An exception is a Python object that represents an error occurring during execution (even
when the code is syntactically correct).

Examples of Exceptions:

 Trying to open a file that doesn’t exist


 Division by zero

When an exception occurs, it is said to be raised and may disrupt program execution.

Why Exception Handling Is Important:

 Prevents abnormal termination of the program.


 Allows programmers to anticipate errors and write exception-handling code to
handle these situations gracefully.

7. What are built-in exceptions in Python, and how do they work?

Built-in exceptions are predefined exceptions that commonly occur during program
execution. These are part of Python's standard library and handle common errors by
displaying the exception name and the reason for the error.

When a built-in exception is raised, the appropriate exception handler is executed, and the
programmer can take further action to resolve the issue.

Chethan M B Arehalli | II PUC (New NCERT Syllabus) | Parikrma Junior College | Computer Science
8. What are some commonly occurring built-in exceptions in Python?

The following are some common built-in exceptions:

Note: Programmers can create user-defined exceptions to handle errors specific to their
program's requirements.

10. How are exceptions raised in Python, and what happens when they are raised?

 Python raises exceptions when errors occur, interrupting normal program flow.
 Exception handlers handle specific errors when they are raised.
 Programmers can also raise exceptions manually using the raise and assert
statements.
 Once an exception is raised, the statements after it in the block won’t be executed.

11. What is the raise statement, and how is it used?

 The raise statement throws an exception manually.

Syntax: raise ExceptionName("Optional error message")

Example: raise Exception("OOPS: An Exception has occurred")

This displays the message and a stack traceback showing the function calls leading to the
exception.

Chethan M B Arehalli | II PUC (New NCERT Syllabus) | Parikrma Junior College | Computer Science
12. What is the assert statement, and how does it work?

 The assert statement tests an expression. If the expression is False, it raises an


AssertionError.

Syntax: assert Expression, "Error message"

Example:

def check_positive(num):
assert num >= 0, "OOPS... Negative Number"
print(num * num)

check_positive(100) # Works fine


check_positive(-10) # Raises AssertionError with the message

When the input is negative, AssertionError is raised, and the remaining statements won’t run.

13. What is exception handling, and why is it important?

Exception handling involves adding extra code to manage errors and prevent the program
from crashing abruptly. It helps provide meaningful error messages or instructions to the
user.

Importance:

 Avoids program crashes during runtime errors.


 Allows handling of both built-in and user-defined exceptions.
 Separates the main program logic from the error-handling code.
 Helps detect the exact error location and type using exception handlers.

14. Explain the process of exception handling in Python. What is throwing and catching
exceptions?

When an error occurs, Python creates an exception object containing details like the error
type, file name, and error position. This object is passed to the runtime system to find the
appropriate exception handler.

Key Steps:

1. Throwing an Exception:
o When an error occurs, Python creates and throws (raises) an exception object.
2. Searching for Exception Handler:
o The runtime searches the program for a suitable exception handler.
o It searches first in the current method, then moves to the caller method in
reverse order through the call stack.
3. Catching the Exception:
o If a handler is found, the exception is caught, and the handler code is executed.
o If no handler is found, the program stops execution.

Chethan M B Arehalli | II PUC (New NCERT Syllabus) | Parikrma Junior College | Computer Science
15. What is catching an exception in Python, and how is it done?

An exception is caught when specific code designed to handle it is executed. Python uses the
try and except blocks to catch exceptions.

Syntax:

try:
[program statements where exceptions might occur]
except [exception-name]:
[code to handle the exception if encountered]

How it Works:

 The try block contains the code where exceptions may occur.
 If an exception occurs, control is transferred to the corresponding except block, and
the rest of the try block is skipped.
 If no exception is encountered, the except block is ignored, and the program continues
normally.

16. What are multiple except blocks, and how do they work in Python?

A single try block may handle multiple types of exceptions by using several except blocks,
each designed to handle a specific error.

Chethan M B Arehalli | II PUC (New NCERT Syllabus) | Parikrma Junior College | Computer Science
Example (Multiple except blocks):

try:
numerator = 50
denom = int(input("Enter the denominator: "))
print(numerator / denom)
print("Division performed successfully")
except ZeroDivisionError:
print("Denominator as ZERO is not allowed")
except ValueError:
print("Only INTEGERS should be entered")

 If ZeroDivisionError occurs, the matching except block handles it.


 If ValueError occurs, the corresponding except block handles it.

17. How can you handle unknown exceptions in Python?

When an exception occurs that is not specifically handled, you can catch it using a generic
except clause without specifying any exception type. This should always be placed last after
other except clauses.

Example (Generic exception handler):

try:
numerator = 50
denom = int(input("Enter the denominator: "))
print(numerator / denom)
except ValueError:
print("Only INTEGERS should be entered")
except:
print("OOPS... SOME EXCEPTION RAISED")

 If any unspecified error occurs, the generic except block will handle it.

18. Explain the purpose of the else clause in exception handling. Write a program to
demonstrate its use.

Answer:
In Python, the else clause is used with the try...except block to specify a block of code that
runs only if no exceptions occur in the try block.

 If an exception is raised, the except block is executed.


 If no exception is raised, the else block is executed after the try block.

Program Example:

try:
numerator = 50
denom = int(input("Enter the denominator: "))
quotient = numerator / denom

Chethan M B Arehalli | II PUC (New NCERT Syllabus) | Parikrma Junior College | Computer Science
except ZeroDivisionError:
print("Denominator cannot be zero.")
except ValueError:
print("Enter a valid integer.")
else:
print("The result is:", quotient)

In this example:

 If the user enters a valid, non-zero denominator, the else block displays the result.
 If the user enters zero or a non-integer, the corresponding except block is executed.

19. What is the finally clause in Python? Explain with an example.

Answer:
The finally clause in Python ensures that a block of code is executed no matter what happens
in the try block, whether an exception occurs or not. It is often used for cleanup operations,
such as closing files or releasing resources.

Example:

print("Handling exception using try...except...else...finally")


try:
numerator = 50
denom = int(input("Enter the denominator: "))
quotient = numerator / denom
print("Division performed successfully")
except ZeroDivisionError:
print("Denominator as ZERO is not allowed")
except ValueError:
print("Only INTEGERS should be entered")
else:
print("The result of division operation is", quotient)
finally:
print("OVER AND OUT")

Explanation:
In this example, the message "OVER AND OUT" will be displayed whether or not an
exception occurs. This ensures proper clean-up and smooth program execution.

20. What happens when an exception is raised but not handled in the try block? Explain
with the finally clause.

Answer:
If an exception is raised in the try block but not handled by any of the except clauses, the
finally block will still execute before the exception is re-raised. This ensures that essential
cleanup (like closing files) happens before the error propagates further.

Chethan M B Arehalli | II PUC (New NCERT Syllabus) | Parikrma Junior College | Computer Science
Example:

print("Practicing for try block")


try:
numerator = 50
denom = int(input("Enter the denominator: "))
quotient = numerator / denom
print("Division performed successfully")
except ZeroDivisionError:
print("Denominator as ZERO is not allowed")
else:
print("The result of division operation is", quotient)
finally:
print("OVER AND OUT")

Explanation:

 If the input is 0, the ZeroDivisionError is handled by the except block, and "OVER
AND OUT" is displayed.
 If non-numeric input is given (e.g., "abc"), a ValueError occurs, which is not
handled. However, "OVER AND OUT" will still be printed due to the finally block,
and the unhandled exception will be re-raised afterward.

Summary:

 try block: Code where exceptions might occur.


 except block: Handles specific exceptions.
 else block: Executes if no exception is raised.
 finally block: Executes whether or not an exception occurs.

****************************************

Chethan M B Arehalli | II PUC (New NCERT Syllabus) | Parikrma Junior College | Computer Science

You might also like