Podcast
Questions and Answers
Every syntax error is an exception, but every exception cannot be a syntax error.
Every syntax error is an exception, but every exception cannot be a syntax error.
True (A)
When is the ImportError exception raised?
When is the ImportError exception raised?
ImportError is raised when the requested module definition is not found.
When is the NameError exception raised?
When is the NameError exception raised?
NameError is raised when a local or global variable name is not defined.
When is the ZeroDivisionError exception raised?
When is the ZeroDivisionError exception raised?
What is the use of a raise
statement?
What is the use of a raise
statement?
Define Exception Handling.
Define Exception Handling.
Define Throwing an exception
Define Throwing an exception
Explain catching exceptions using try
and except
block.
Explain catching exceptions using try
and except
block.
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 _____:
print (" Please enter only numbers")
except _____:
print(" Number 2 should not be zero")
else:
print(" Great ... you are a good programmer")
finally:
print(" JOB OVER... GO GET SOME REST")
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 _____:
print (" Please enter only numbers")
except _____:
print(" Number 2 should not be zero")
else:
print(" Great ... you are a good programmer")
finally:
print(" JOB OVER... GO GET SOME REST")
Flashcards
Syntax Errors
Syntax Errors
Errors detected when the rules of a programming language are not followed; also known as parsing errors.
Exception
Exception
An error that occurs even if a statement is syntactically correct, disrupting program execution.
Built-in Exceptions
Built-in Exceptions
Predefined errors readily available in the compiler/interpreter.
Raise Statement
Raise Statement
Signup and view all the flashcards
Assert Statement
Assert Statement
Signup and view all the flashcards
Exception Handling
Exception Handling
Signup and view all the flashcards
Try Block
Try Block
Signup and view all the flashcards
Except Block
Except Block
Signup and view all the flashcards
Else Clause
Else Clause
Signup and view all the flashcards
Finally Clause
Finally Clause
Signup and view all the flashcards
Exception Object
Exception Object
Signup and view all the flashcards
Throwing an Exception
Throwing an Exception
Signup and view all the flashcards
Exception Handler
Exception Handler
Signup and view all the flashcards
Hierarchical Search
Hierarchical Search
Signup and view all the flashcards
Study Notes
- A quote by Bjarne Stroustrup says code should be elegant, efficient, and straightforward for error handling and minimal dependencies.
Introduction
- When a Python program is executed, it can generate unexpected outputs or behave abnormally, or not execute at all.
- Syntax, runtime, and logical errors in code are root causes of such failures.
- Errors known as exceptions in Python, are automatically triggered but can be handled through program code.
- The chapter focuses on learning about exception handling in Python programs.
Syntax Errors
- Syntax errors occur when the rules of a programming language has not been followed while writing code, and are also known as parsing errors.
- The interpreter does not execute the program unless syntax errors are rectified, saved, and the program is rerun.
- Python displays the error name and a brief description when syntax errors are encountered in shell mode.
- When a syntax error is encountered, a dialog box displays the error details while running a program in script mode.
Exceptions
- Errors can arise during program execution even if a statement or expression is syntactically correct.
- Exceptions might disrupt the normal execution of a program, such as trying to open a nonexistent file or dividing by zero.
- An exception signifies an object in Python which represents an error.
- A programmer needs to handle an exception so that the program does not terminate abnormally.
- Programmers should anticipate erroneous situations while designing a program and address them by including relevant code to handle the exception.
- A SyntaxError is also an exception, but all other exceptions are generated when a program is syntactically correct.
Built-in Exceptions
- Commonly occurring exceptions that are defined in the compiler/interpreter are known as built-in exceptions.
- Python's standard library has a large collection of built-in exceptions for commonly occurring errors, which provide standardized solutions.
- When a built-in exception occurs, the appropriate exception handler code is executed, displaying the reason along with the exception name.
- The programmer must ensure appropriate action is taken to handle it.
Common Built-in Exceptions
SyntaxError
: Raised when there is an error in the Python code syntax.ValueError
: Raised when a built-in method or operation receives an argument with the correct data type but an inappropriate value.IOError
: Raised when the specified file cannot be opened in a program statement.KeyboardInterrupt
: Raised when the user accidentally presses Delete or Esc keys during program execution, interrupting the normal flow.ImportError
: Raised when the requested module definition is not found.EOFError
: Raised when the end-of-file condition is reached without any data read by input().ZeroDivisionError
: Raised when the denominator in a division operation is zero.IndexError
: Raised when a sequence index is out of range.NameError
: Raised when a local or global variable name is not defined.IndentationError
: Raised due to incorrect program code indentation.TypeError
: Raised when an operator has an incorrect data type value.OverflowError
: Raised when the result of a calculation exceeds the maximum limit for the numeric data type.- The Python interpreter raises ZeroDivisionError, NameError, and TypeError under different situations.
- Programmers have the option to create custom exceptions called user-defined exceptions.
Raising Exceptions
- Each time an error is detected, the Python interpreter raises (throws) an exception.
- Exception handlers are designed to execute when a specific exception is raised.
- The
raise
andassert
statements can forcefully raise exceptions in a program. - The current block of code will not execute further, once an exception has been raised.
- Exception raising interrupts normal execution and jumps to the part of the program written to handle the situation.
The raise
Statement
- This can be used to throw an exception, using the syntax:
raise exception-name[(optional argument)]
. - An argument, usually a string, can be displayed when the exception is raised.
- Errors detected can be either built-in or user-defined exceptions.
- The
raise
statement can raise built-in exceptions such asIndexError
. - If
IndexError
is raised, subsequent statements will not be executed, and "NO EXECUTION" will not be displayed. - A stack traceback is displayed along with the error message.
- The stack contains about the sequence of function calls in the part of code where the exception occurred.
- The error is found in the most recently called function.
The assert
Statement
- This statement is used to test an expression in a program.
- If the test result is false, an exception is raised.
- Generally used at the beginning of a function or after a function call to check for valid input.
- The syntax is
assert Expression[,arguments]
. - Python evaluates the expression after the assert keyword and if the expression is false, an
AssertionError
exception is raised. - When the number is negative,
AssertionError
will be triggered and subsequent statements are not executed.
Handling Exceptions
- Programmers handle all exceptions to prevent program crashes, which is done by writing additional code to give instructions to the user.
- The process of providing messages to the user upon encountering an exception is known as exception handling.
Need for Exception Handling
- It is useful in capturing runtime errors in Python, C++, Java, Ruby, and similar languages.
- Exception handling helps avoid program crashes.
- Python categorizes exceptions into distinct types, so specific exception handlers can be created for each type.
- Exception handlers separate the error detection and correction code from the main logic of the program.
- Code liable to error and code to run when the error occurs, are placed in different blocks.
- The compiler or interpreter keeps track of the exact error position.
- Both user-defined and built-in exceptions can be handled.
Process of Handling Exceptions
- When an error occurs, the Python interpreter generates an "exception object".
- The object contains info about the error like type, file name, and position.
- The exception object is handed over to the runtime system to find suitable code to handle it.
- The process of creating an exception object and handing it over to the runtime system is called "throwing" an exception.
- When an exception occurs, the control jumps to an exception handler, abandoning the execution of the remaining statements.
- The runtime system searches the program for a code block, called the "exception handler", that can handle the exception.
- The search occurs in the method where the error occurred and exception was raised.
- If not found, the method from which this method was called is searched.
- Reverse order is followed until the exception handler is found and the list of methods is known as call stack.
- When a suitable handler is found in the call stack, it is executed by the runtime process.
- Executing a suitable handler is "catching the exception.".
- The program stops when the runtime system cannot find an appropriate exception after searching every method in the call stack.
Catching Exceptions
- When a code designed to handle a particular exception is executed, an exception is said to have been 'caught'.
- Exceptions are caught in the
try
block and handled in theexcept
block. - Suspicious lines of code that might cause exceptions are placed inside a
try
block. - A
try
block is followed by anexcept
block and the code to handle each possible exception inside thetry
block are written inside theexcept
clause. - When an exception occurs in the
try
block during execution, further execution is stopped and transferred to theexcept
block. - The syntax of the
try
...except
clause istry:
followed by program statements, andexcept [exception-name]:
followed by exception handling code. - The ZeroDivisionError exception is handled, and the print statement executes printing if the user enters a non-zero denominator value.
- In this scenario, the
except
clause is skipped and the message "OUTSIDE try..except block" will be printed. - The control shifts to the
except
block and the message "Denominator as Zero.... not allowed" is printed If the value of denom is zero. - The "OUTSIDE try..except block" text is still printed.
Multiple Except Clauses
- One may suspect there could be more than one type of error in some code, so multiple
except
blocks will need to be set up. - Two types of exceptions (ZeroDivisionError and ValueError) can be handled with two
except
blocks. - When an exception is raised, the code searches for the matching
except
block until it is handled. - The program will terminate if there is no match.
- All exceptions without a handler can be handled by adding an
except
clause without specifying any exception but must be added as the last clause. - Without a handler for ZeroDivisionError, the last
except
clause will execute, printing "OOPS.....SOME EXCEPTION RAISED".
Try/Except/Else Clause
- An optional else clause can exist in conjunction with the
try
...except
clause. - An
except
block will only be executed if some exception is raised in thetry
block. - The statements inside the
else
clause will be executed when there is no error with none of theÂexcept
blocks being executed.
Finally Clause
- The try statement in Python can also have an optional finally clause.
- The statements inside the finally block or always have executed regardless of whether an exception has occurred in the
try
block or not. - The
finally
clause is commonly used while working with files. - If used, the
finally
clause is placed as the end of thetry
clause.
Recovering and Continuing with Finally Clause
- If an error has been detected in the try block and the exception has been thrown, the appropriate except block will be executed to handle the error if it's handled by any of the except clauses.
- After execution of the
finally
block, Python transfers the control to a previously entered try or to the next higher level default exception handler - That is unlike except, execution of the finally clause does not terminate the execution Rather, the exception continues to be raised after execution of finally.
- To summarise, code where there are potential errors is included in a
try
block, the codes to handle the corresponding exception are included in theexcept
clause, and the optionalelse
clause has the code to be executed in no exception occurs. The optionalfinally
block always needs to be executed.
Studying That Suits You
Use AI to generate personalized quizzes and flashcards to suit your learning preferences.