FoCT - T15
FoCT - T15
Computational Thinking
AoC, exception handling and logging
Ao
Logging
4593387-bfb0319b
Plaksha Leaderboard 2024
Ao
Outline Exception
Logging
Exception is an event that occurs during the execution of a program and disrupts the normal flow of
instructions.
Most of the built-in exception in Python deal with situations in which a program has attempted to execute a
When an exception is raised, the program terminates (crashes), but does not necessarily need to lead to
program termination.
When an exception is raised that causes the program to terminate, we say that an unhandled exception has
been raised.
Application tries to load an image from the system, but the image is not foun
Application expects a value in the range 41 to 65 and the user inputs a valid that is not within the specified rang
Application is trying to access a database and the connection to the database fail
Application has loaded a lot of data and application runs out of memor
Application tries to read from a file, but the file does not exist
Exceptions, when raised, can be handled by the program and is something a programmer can and should
anticipate.
While if...else blocks can be used to check error prone conditions, the try...except block is better
try:
except <exception_name>:
Code that might raise an exception is placed in the try block and in the case that an exception occurs, the code
Code block
Except
Log error, exit etc. Continues execution
block
Start by identifying the code that may cause an exception to occur
def read_from_file(filename):
file_handle = open(filename,"r")
line = file_handle.read()
for word in line.split():
print(word)
file_handle.close()
if __name__ == '__main__':
filename = input("Enter the name of the file: ")
read_from_file(filename)
Start by identifying the code that may cause an exception to occur
file_handle = open(filename,"r")
line = file_handle.read()
line.split():
print(word)
file_handle.close()
filename = input(
read_from_file(filename)
Put this inside a try block, this will be tested for errors when executed
try:
file_handle = open(filename,"r")
line = file_handle.read()
line.split():
print(word)
file_handle.close()
filename = input(
read_from_file(filename)
Next, add an except block to add the exception handling code
try:
file_handle = open(filename,"r")
except IOError:
print("Error! File " + filename + "is not found!")
line = file_handle.read()
line.split():
print(word)
file_handle.close()
read_from_file(filename)
Here you should also specify the type of exception that is being expected by the potentially erroneous code.
Lastly, add the code that is to be executed in case an exception does not occur i.e., ideal case
def read_from_file(filename):
try:
file_handle = open(filename,"r")
except IOError:
else:
line = file_handle.read()
print(word)
file_handle.close()
if __name__ == '__main__':
read_from_file(filename)
You can define your own exceptions in Python which allow you to handle more granular errors and errors that may
This is done exactly the same way as a class is defined, inheriting from the built-in Exception base class (on
class CustomException(Exception):
super().__init__(self.message)
These exceptions can be raised using the raise keyword when a given condition is encountered.
An assertion is a sanity-check that can replace the if-raise statement.
An expression is tested, and if the result comes up false, an exception (AssertionError) is raised.
val = x / y
return val
Ao
Outline Exception
Logging
Beyond adding checks to your code, it is also imperative to be able to trace back to the source of the error when
Logging errors and runtime information can help in the debugging process and is more graceful than adding print
Python provides a logging module with configurations and varying levels of logging information.
import logging
logging.basicConfig(filename='app.log', level=logging.DEBUG,
INFO: Confirmation that things are working as expected. This is the level you would use for normal operations
and informational messages
WARNING: An indication that something unexpected happened, or indicative of some problem in the near future
(e.g., "disk space low"). The software is still working as expected
ERROR: Due to a more serious problem, the software has not been able to perform some function. An error
indicates a significant issue that needs attention
CRITICAL: A very serious error, indicating that the program itself may be unable to continue running. Critical
errors often represent severe problems that require immediate action.
fin