[go: up one dir, main page]

0% found this document useful (0 votes)
5 views19 pages

FoCT - T15

Uploaded by

ishratayeshab
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)
5 views19 pages

FoCT - T15

Uploaded by

ishratayeshab
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/ 19

Fundamentals of

Computational Thinking
AoC, exception handling and logging
Ao

Outline Errors and Exception

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

statement with no appropriate semantics.

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 occasionally receives zero as the value for the diviso

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

suited and especially built to handle exceptions.

try:

<code that might raise an exception>

except <exception_name>:

<code to handle the exception>

Code that might raise an exception is placed in the try block and in the case that an exception occurs, the code

in the except block is executed.


Try
block

Code block

Exception occurs No exception

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:

print("Error! File " + filename + "is not found!")

else:

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)
You can define your own exceptions in Python which allow you to handle more granular errors and errors that may

be encountered in user defined classes.

This is done exactly the same way as a class is defined, inheriting from the built-in Exception base class (on

which all exception types are based).

class CustomException(Exception):

def __init__(self, message):

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.

def divide(x, y):

assert y != 0, 'Cannot divide by zero'

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

running large programs.

Logging errors and runtime information can help in the debugging process and is more graceful than adding print

statements to various parts of the code.

Python provides a logging module with configurations and varying levels of logging information.

import logging

# Set up the basic configuration for logging

logging.basicConfig(filename='app.log', level=logging.DEBUG,

format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# Log messages of various severity levels

logging.debug('This is a debug message')

logging.info('This is an info message')

logging.warning('This is a warning message')

logging.error('This is an error message')

logging.critical('This is a critical message')


DEBUG: Detailed information, typically of interest only when diagnosing problems. Used for debugging purposes
during development

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

You might also like