NCERTCh 1Free

h apter

🎓 Class 12📖 Computer Science📖 10 notes🧠 15 Q&A⏱️ ~15 min

h apterStudy Notes

NCERT-aligned · 10 notes · 3 shown free

1.1 INTRODUCTION

Explanation

1.1 INTRODUCTION

In Python programming, during the execution of a program, various types of errors can occur that affect the program's normal flow. These errors may cause the program to either not execute at all, produce unexpected output, or behave abnormally. Such errors are broadly categorized as syntax errors, runtime errors, and logical errors. Syntax errors occur when the rules of the programming language are violated, preventing the program from executing. Runtime errors, also known as exceptions, occur during the execution phase even if the program is syntactically correct. Logical errors are mistakes in the program's logic that cause incorrect results but do not necessarily halt program execution. Exceptions in Python are special error objects that are automatically triggered when an error condition arises during program execution. These exceptions disrupt the normal flow of the program. However, Python provides mechanisms to forcefully trigger exceptions and to handle them gracefully within the program code. Exception handling is essential to ensure that the program does not terminate abruptly and can recover or provide meaningful feedback to the user. This chapter focuses on understanding exceptions in Python, the types of exceptions, and how to handle them effectively through various constructs such as try, except, raise, assert, else, and finally clauses.

  • Errors during program execution can be syntax, runtime, or logical errors.
  • Exceptions are runtime errors that disrupt normal program flow.
  • Python automatically raises exceptions when errors occur during execution.
  • Programmers can also raise exceptions intentionally using code.
  • Exception handling prevents abrupt program termination and allows graceful recovery.
  • This chapter covers various aspects of exception handling in Python.
  • 📌 Exception: A Python object representing an error during program execution.
  • 📌 Syntax Error: An error due to violation of programming language syntax rules.
  • 📌 Runtime Error: An error occurring during program execution despite correct syntax.

1.2 SYNTAX ERRORS

Explanation

1.2 SYNTAX ERRORS

Syntax errors occur when the programmer does not follow the rules of the Python language while writing code. These errors are also called parsing errors because the interpreter cannot parse the code correctly. When a syntax error is present, the Python interpreter halts execution and displays an error message indicating the type of error and a brief description to help the programmer correct it. In shell mode, when a syntax error is encountered, Python displays the error name and a short message explaining the error. For example, if a colon is missing after a conditional statement, the interpreter will raise a SyntaxError and show a message indicating the issue. In script mode, when running a Python program file, if a syntax error exists, a dialog box appears specifying the error name and a description. The program will not execute until the syntax errors are corrected and the program is saved and rerun. Syntax errors must be fixed before the program can run successfully. They are the first type of errors detected by the interpreter, and handling them is crucial for the program to proceed to execution.

  • Syntax errors occur due to violation of Python language rules.
  • Also known as parsing errors.
  • Detected before program execution.
  • Python interpreter displays error name and description.
  • Program execution halts until syntax errors are fixed.
  • Errors can be seen in both shell and script modes.
  • 📌 Syntax Error: An error caused by incorrect syntax in the program code.
  • 📌 Parsing Error: Another term for syntax error, indicating failure to parse code.

1.3 EXCEPTIONS

Explanation

1.3 EXCEPTIONS

Exceptions are errors that occur during the execution of a syntactically correct Python program. Unlike syntax errors, exceptions arise when a statement or expression is valid in form but causes an error during runtime. Examples include attempting to

Practice Questionsh apter

Includes NCERT exercise questions with answers

Q1.1. “Every syntax error is an exception but every exception cannot be a syntax error.” Justify the statement.

Answer:

A syntax error occurs when the code violates the rules of the programming language grammar, such as missing a colon or parentheses. These errors are detected by the interpreter before the program runs and are a type of exception. However, exceptions also include runtime errors like division by zero or file not found, which are not syntax errors but logical or runtime errors. Therefore, every syntax error is an exception because it disrupts normal execution, but not every exception is a syntax error since exceptions also include runtime errors.

Explanation:

Syntax errors are a subset of exceptions that occur due to incorrect code structure. Exceptions include all errors that disrupt normal flow, including runtime errors. Hence, all syntax errors are exceptions, but exceptions can also be other types of errors.

MediumNCERT
Q2.2. When are the following built-in exceptions raised? Give examples to support your answers. a) ImportError b) IOError c) NameError d) ZeroDivisionError

Answer:

a) ImportError: Raised when an import statement fails to find the module definition or when a module cannot be loaded. Example: try: import non_existent_module except ImportError: print("Module not found") b) IOError: Raised when an input/output operation fails, such as failing to open a file. Example: try: f = open('non_existent_file.txt') except IOError: print("File not found or can't be opened") c) NameError: Raised when a local or global name is not found. Example: try: print(undefined_variable) except NameError: print("Variable not defined") d) ZeroDivisionError: Raised when division or modulo by zero takes place. Example: try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero")

Explanation:

Each exception is raised under specific conditions: - ImportError: when import fails - IOError: when file operations fail - NameError: when an undefined variable is accessed - ZeroDivisionError: when dividing by zero Examples demonstrate typical scenarios causing these exceptions.

MediumNCERT
Q3.3. 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).

Answer:

The raise statement is used to explicitly throw an exception in Python. It allows the programmer to trigger an exception manually. Example code: try: num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) if num2 == 0: raise ZeroDivisionError("Denominator cannot be zero") quotient = num1 / num2 print("Quotient is", quotient) except ZeroDivisionError as e: print("Error:", e) except ValueError: print("Please enter valid numbers")

Explanation:

The raise statement is used to throw an exception when a specific condition occurs, such as division by zero. The code accepts two numbers, checks if the denominator is zero, raises ZeroDivisionError if so, otherwise performs division and prints the quotient.

MediumNCERT
Q4.4. Use assert statement in Question No. 3 to test the division expression in the program.

Answer:

The assert statement is used to test if a condition is true. If the condition is false, it raises an AssertionError. Modified code using assert: try: num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) assert num2 != 0, "Denominator cannot be zero" quotient = num1 / num2 print("Quotient is", quotient) except AssertionError as e: print("Error:", e) except ValueError: print("Please enter valid numbers")

Explanation:

The assert statement checks that the denominator is not zero before performing division. If num2 is zero, it raises an AssertionError with the message. This is an alternative to raising exceptions explicitly.

MediumNCERT
Q5.5. Define the following: a) Exception Handling b) Throwing an exception c) Catching an exception

Answer:

a) Exception Handling: It is the process of responding to the occurrence of exceptions (errors) during the execution of a program to prevent the program from crashing. b) Throwing an exception: It means explicitly causing an exception to occur using the raise statement. c) Catching an exception: It means handling the exception using try and except blocks to prevent the program from terminating abruptly.

Explanation:

Definitions clarify the concepts: - Exception Handling manages errors gracefully. - Throwing an exception is generating an error intentionally. - Catching an exception is intercepting and managing errors.

EasyNCERT
Q6.6. Explain catching exceptions using try and except block.

Answer:

Catching exceptions using try and except blocks involves placing the code that might raise an exception inside a try block. If an exception occurs, the control is transferred to the except block where the exception can be handled gracefully. Example: try: x = int(input("Enter a number: ")) y = 10 / x print(y) except ZeroDivisionError: print("Cannot divide by zero") except ValueError: print("Invalid input") This prevents the program from crashing and allows for error messages or alternative flows.

Explanation:

The try block contains code that may cause exceptions. The except block catches specific exceptions and handles them, ensuring the program continues or terminates gracefully.

EasyNCERT
Q7.7. Consider the code given below and fill in the blanks. ```python print ("Learning Exceptions...") try: num1 = int(input("Enter the first number")) num2 = int(input("Enter the second number")) quotient = (num1 / num2) print("Both the numbers entered were correct") except __________ : # to enter only integers print("Please enter only numbers") except __________ : # Denominator should not be zero print("Number 2 should not be zero") else: print("Great .. you are a good programmer") __________ : # to be executed at the end print("JOB OVER... GO GET SOME REST") ```

Answer:

The blanks should be filled as follows: except ValueError: # to enter only integers except ZeroDivisionError: # Denominator should not be zero finally: # to be executed at the end Complete code: print ("Learning Exceptions...") try: num1 = int(input("Enter the first number")) num2 = int(input("Enter the second number")) quotient = (num1 / num2) print("Both the numbers entered were correct") except ValueError: print("Please enter only numbers") except ZeroDivisionError: print("Number 2 should not be zero") else: print("Great .. you are a good programmer") finally: print("JOB OVER... GO GET SOME REST")

Explanation:

ValueError is raised when input cannot be converted to int, ZeroDivisionError when denominator is zero, and finally block executes regardless of exceptions.

MediumNCERT
Q8.8. You have learnt how to use math module in Class XI. Write a code where you use the wrong number of arguments for a method (say sqrt() or pow()). Use the exception handling process to catch the ValueError exception.

Answer:

Example code: import math try: # Calling sqrt() with two arguments instead of one result = math.sqrt(16, 4) except TypeError as e: print("Error:", e) # Alternatively, if ValueError is expected (e.g., sqrt of negative number): try: result = math.sqrt(-4) except ValueError as e: print("Error:", e) Explanation: Passing wrong number of arguments to math.sqrt() raises TypeError, which can be caught using try-except. Passing invalid values (like negative number) raises ValueError.

Explanation:

The math.sqrt() function expects exactly one argument. Passing two arguments raises TypeError. Passing invalid values raises ValueError. Exception handling with try-except can catch these errors and prevent program crash.

MediumNCERT