We handle errors or exceptions in a program using exception handling in Python. When an error occurs during the execution of a program, exceptions are thrown in Python. Exception handling allows us to handle these errors and prevent the program from crashing. we use theattempt
miexcept
Declarations for handling exceptions in Python. EITHERattempt
The block contains the code that can throw an exception and the correspondingexcept
The block contains the code to handle the exception.
Index
1. "Every syntax error is an exception, but every exception cannot be a syntax error." Justify the statement.
This statement means that not all exceptions in Python are syntax errors, but all syntax errors are exceptions.
A syntax error is a type of exception that occurs when the Python interpreter encounters invalid syntax in your code, such as missing parentheses or incorrect indentation. These errors prevent the code from running because the interpreter cannot understand the code as it is written.
However, there are other types of exceptions in Python that are not related to syntax errors. For example, an exception may be thrown when a program tries to divide by zero, or when a program tries to access a list index that is out of range. These exceptions occur during the execution of the program and are not related to the syntax of the code.
Therefore, the statement "Every syntax error is an exception, but every exception cannot be a syntax error" is true because all syntax errors are exceptions, but not all exceptions are syntax errors.
2. When are the following built-in exceptions thrown? Give examples to support your answers.
- ImportError
- IOError
- name error
- zero division error
a) When theImportError
Inner exceptions raised in Python?
OImportError
inner exceptiongenerated in Python when an imported module or its dependencies cannot be found. This exception is thrown when the Python interpreter cannot find the specified module in amatter
declaration or when the module or its dependencies throw an import error.
For example, the following code generates aImportError
if the moduleexample_module
not found in current environment:
1 | matterexample_module |
This exception is usually thrown when a required module or its dependencies are not installed or cannot be accessed in the current environment. To handle this exception, you can wrap thematter
statement in aattempt
–except
block and provide an appropriate error message or alternate code to execute when the exception is thrown.
b) When theIOError
Inner exceptions raised in Python?
OIOError
inner exceptiongenerated in Python when there is an input/output error, such as an error reading or writing a file. for example, oneIOError
can be generated if a file that a program tries to read does not exist or if the program does not have permission to access the file. It can also occur if a program tries to write to a file that it does not have permission to modify, or if there is a problem with the storage device the file is stored on.
Here is an example of how theIOError
the exception can be raised in python:
1 2 3 4 5 | attempt: comOpened("file.txt") as F: Given = F.further() exceptIOError: print("An error occurred while trying to read the file.") |
c) When thename error
Inner exceptions raised in Python?
Oname error
inner exceptiongenerated in Python when a name (variable, function, class, etc.) is not found in the current namespace. This usually means that the name has not been defined or is misspelled.
For example, if you try to use a variable that has not been defined, you will get aname error
:
1 2 3 4 | >>> print(X) Follow-up (furtherrecentcallto last): Archive "<std input>", line 1, they <module> name error: name 'X' it is No defined |
Also, if you try to call a function that hasn't been defined, you'll also get aname error
:
1 2 3 4 | >>> my function() Follow-up (furtherrecentcallto last): Archive "<std input>", line 1, they <module> name error: name 'my role' it is No defined |
d) When thezero division error
Inner exceptions raised in Python?
Ozero division error
An internal exception is thrown in Python when a program tries to divide a number by zero. For example:
1 2 3 | >>> X = 5 >>> y = 0 >>> print(X/y) |
This exception can be handled using aattempt
–except
block to provide a more meaningful error message or to handle the error in a different way. For example:
1 2 3 4 | attempt: result = 5 / 0 exceptzero division error: print("You can't divide by zero.") |
Ozero division error
The exception indicates that an attempt was made to divide by zero, which is not defined in mathematics. In Python, this exception is thrown to prevent incorrect results and to indicate that there is a problem with the code. To handle this exception, you can use aattempt
miexcept
block your code to catch the exception and handle it accordingly.
3. What is the use of a raise statement? Write code to accept two numbers and display the quotient. The appropriate exception should be thrown if the user enters the second number (denominator) as zero (0).
Oelevation
The declaration is used to explicitly raise an exception in Python. It can be used to handle specific cases and provide custom error messages.
Here's some code that takes two numbers as input and displays their quotient. An appropriate exception is thrown if the user enters the second number (denominator) as zero (0):
1 2 3 4 5 6 7 8 | numero1 = float(Forbidden("Enter the first number: ")) numero2 = float(Forbidden("Enter the second number: ")) And if numero2 == 0: elevationexception("The denominator cannot be zero") other: quotient = numero1 / numero2 print("The Quotient of", numero1, "mi", numero2, "Es", quotient) |
4. Use the assertion statement in Question #3 to prove the division expression in the program.
1 2 3 4 5 6 7 8 | numero1 = float(Forbidden("Enter the first number: ")) numero2 = float(Forbidden("Enter the second number: ")) And if numero2 == 0: elevationexception("The denominator cannot be zero") other: quotient = numero1 / numero2 print("The Quotient of", numero1, "mi", numero2, "Es", quotient) |
5. Set the following:
- exception handling
- throwing an exception
- catching an exception
exception handling
exception handlingin Python allows you to handle errors and exceptions that occur during the execution of a program. This helps prevent the program from crashing and allows you to provide a custom error message or take other steps to fix the error.
The basic structure of exception handling in Python is as follows:
1 2 3 4 | attempt: # code that can throw an exception exceptexception type: # code to handle the exception |
Here is an example of how you can use exception handling to handle azero division error
What happens when you divide a number by zero?
1 2 3 4 5 6 7 | attempt: numero1 = float(Forbidden("Enter the first number: ")) numero2 = float(Forbidden("Enter the second number: ")) quotient = numero1 / numero2 print("The Quotient of", numero1, "mi", numero2, "Es", quotient) exceptzero division error: print("You can't divide by zero.") |
In this example, the code inattempt
The block prompts the user for two numbers and calculates their quotient. If the user enters a value of 0 for the second number (denominator), azero division error
will be raised. The code in the except block handles this error by printing a "Cannot divide by zero" message. The program continues to run after the error is fixed.
throwing an exception
Throwing an exception in Pythonit means to explicitly raise an exception in your code to signal an error or abnormal situation. The raise statement is used to throw an exception in Python.
For example, consider a function that accepts a value and throws an exception if the value is negative:
1 2 3 4 5 | definitelypositive number(valor): And if valor < 0: elevationValueError("The value must be positive.") other: print("The value is positive.") |
In this example, if the value passed to thepositive number
the function isnegative
, the raise statement generates aValueError
exception with "Value must be positive" message. The caller of the function can catch the exception using aattempt
–except
block to handle it correctly.
1 2 3 4 | attempt: positive number(-5) exceptValueErroras mi: print("Error:", mi) |
This code will produce:
1 | Error: Valorhe mustto bepositive. |
catching an exception
Catching an exception in Pythonmeans to handle an exception that is thrown during the execution of a program. This is done using aattempt
–except
block. Code that might throw an exception is placed in theattempt
block, and the code to handle the exception is placed in the correspondingexcept
block.
1 2 3 4 5 6 7 8 9 10 | attempt: numero1 = float(Forbidden("Enter the first number: ")) numero2 = float(Forbidden("Enter the second number: ")) result = numero1 / numero2 exceptzero division error: print("You can't divide by zero.") exceptValueError: print("Invalid input. Only numbers allowed.") other: print("The result is", result) |
In this example, the program accepts two numbers as user input and divides the first number by the second number. If the second number is zero, onezero division error
gets up and stays onexcept
block and the message "Cannot divide by zero" appears. If the user enters something other than a number, aValueError
is lifted and secured in the correspondingexcept
block and the message “Invalid input. Only numbers are allowed. is displayed. If no exception is thrown, the result of the division will be printed.
6. Explain exception catching using the test and exception block.
Oattempt
miexcept
blocks are used in pythonto handle exceptions or runtime errors. Code that might throw an exception is contained in a test block. If an exception occurs, the code inside theexcept
the block is executed. EITHERexcept
The block provides the opportunity to handle the exception normally instead of letting the program crash.
Here is an example of how you can use the try and except blocks:
1 2 3 4 5 6 7 8 9 10 11 12 | attempt: # some code that might throw an exception result = And t("a") exceptValueErroras UE: # code to handle the exception print("Error: Cannot convert string to integer.") exceptexceptionas mi: # generic exception handler print("An error occurred:", calle(mi)) other: # code to execute if there is no exception print("Result:", result) |
In this example, the code inside theattempt
The block attempts to convert a string to an integer. Since the string is not a valid integer, aValueError
an exception is raised. EITHERexcept
deal block withValueError
exception and prints an error message. If no exception is thrown, the code inside the else block will be executed.
7. Consider the following code and fill in the blanks
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | print ("Learning Exceptions...") attempt: numero1= And t(Forbidden ("Enter the first number")) numero2=And t(Forbidden("Enter the second number")) quotient=(numero1/numero2) print ("Both numbers entered were correct") except_____________: # to enter only integers print ("Enter numbers only") except____________: # The denominator must not be zero print("The number 2 must not be zero") other: print("Great... you're a good programmer") ___________: # to be executed at the end print("JOB DONE... GO REST") |
Respondedor:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | print ("Learning Exceptions...") attempt: numero1= And t(Forbidden ("Enter the first number")) numero2=And t(Forbidden("Enter the second number")) quotient=(numero1/numero2) print ("Both numbers entered were correct") exceptValueError: # to enter only integers print ("Enter numbers only") exceptzero division error: # The denominator must not be zero print("The number 2 must not be zero") other: print("Great... you're a good programmer") finally: # to be executed at the end print("JOB DONE... GO REST") |
8. You learned to use the math module in Class XI. Write code where you use the wrong number of arguments to a method (for example, sqrt() or pow()). Use the exception handling process to catch the ValueError exception.
Here's an example of how to use exception handling to catch the ValueError that is raised when the wrong number of arguments are used to the math.sqrt() method:
1 2 3 4 5 6 7 8 9 10 11 12 | mattermathematics attempt: X = float(Forbidden("Enter a number to find its square root: ")) result = mathematics.square(X, 2) # provide two arguments instead of one exceptValueErroras UE: print("Error: invalid argument to sqrt() method.") print("Message:", calle(UE)) exceptexceptionas mi: print("An error occurred:", calle(mi)) other: print("square root of", X, "Es", result) |
In this code, the user is asked to enter a number. The square root of the entered number is calculated using themath.sqrt()
method. Since we supply two arguments instead of one, oneValueError
an exception is raised. EITHERexcept
block take theValueError
exception, prints an error message and continues with the next line of code. If no exception is thrown, the code inside theother
the block is executed.
9. What is the use of the finally clause? Use the finally clause in the problem given in Question #7.
Ofinally
The clause in Python is used to specify a block of code that will be executed anyway. EITHERfinally
The clause is placed after theexcept
clause(s) in aattempt
statement.
The purpose of the final clause is to ensure that some code is executed regardless of whether or not an exception has been thrown. For example, you can use thefinally
clause to close a file that was opened in theattempt
lock or release a resource that has been acquired.
Use the finally clause in the problem given in Question #7.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | print ("Learning Exceptions...") attempt: numero1= And t(Forbidden ("Enter the first number")) numero2=And t(Forbidden("Enter the second number")) quotient=(numero1/numero2) print ("Both numbers entered were correct") exceptValueError: # to enter only integers print ("Enter numbers only") exceptzero division error: # The denominator must not be zero print("The number 2 must not be zero") other: print("Great... you're a good programmer") finally: # to be executed at the end print("JOB DONE... GO REST") |
CBSE syllabusCBSE Python Programaerror handlingexception handlingException Handling in Python NCERTNCERT Python SyllabusNCERT curriculumPython error handlingPython CBSE error handlingPython exceptionsExceptions to Python CBSEPython test, except NCERTBloque Try-Except
Isrg Buzz team
The Isrg Buzz team is comprised of seasoned writers, analytics experts, seasoned editors, and well-rounded researchers, providing top-notch content and information to clients. Whether writing, analyzing data, editing, or supporting research, they use their diverse skill sets to deliver exceptional results.