Day 16. Exceptional Handling, DateTime, JSON module in python.

Hello Everyone..

Today, we are going to do how we can identify the errors and how to control it. in python, we can call that exceptional handling, we can also discussing the DateTime module, how we can use it in the program and also we can go to discuss JSON.

The topics we can discuss today:-

  • Exceptional Handling.
  • DateTime Module.
  • JSON

Let’s Start..

1. Exceptional Handling.

  • An exception is an error that happens during the execution of a program.
  • An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program’s instructions.
  • An exception is a Python object that represents an error.
  • Exception handling is a construct in some programming languages to handle or deal with errors automatically.
  • If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block includes an except statement, followed by a block of code which handles the problem as elegantly as possible.
  • The else: block executes if the code in the tey: block does not raise an exception.
  • The finally: block is a place to put any code that must execute, whether the try-block raised an exception or not.
try:
You do your operations here
...........................
except Exception1:
If there is Exception1, then execute this block.
except Exceptional2:
If there is Exceptional2. then execute this block.
........................
else:
If there is no exception then execute this block.
finally:
This would always be axecuted.
..........................
  • An exception can have an argument, which is a value that gives additional information about the problem.
  • The contents of the arguments vary by exception.
  • You capture an exception argument by supporting a variable in the except clause as follows —
try:
You do your operations here
.......................
except: ExceptionType as Argument:
You can print valus of Argument here...

The except Clauses with No Exceptions.

  • This kind of a try-except statement catches all the exceptions that occur.
  • Using this kind of try-except statement is not considered a good programming practice though, because it catches all exceptions but does not make a programmer identify the root clause of the problem that may occur.
try:
You do your operations here
.......................
except:
If there is any exception,them execute this block.
else:
If there is no exception then execute this block.
  • You can raise exceptions in several ways by using the raise statement.
raise [Exception [,args [,traceback]]]
  • Python allows the user to create his own exception by deriving classes from the standard built-in exceptions.
  • For example, let’s create an exception from RuntimeError. Here, a class is created that is subclassed from Runtime Error.
  • This is useful when you need to display more specific information when an exception is caught
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
  • So once you have defined the above class, you can raise the exception as follows -
try:
raise Networkerror("Bad hostname")
except:
print e.args

2. Datetime.

  • The DateTime module supplies classes for manipulating dates and times in both simple and complex ways.
  • There are two kinds of date and time objects: naive and aware.

Naive

  • A naive object does not contain enough information to unambiguously locate itself relative to other date/time objects.
  • Whether a naive object represents Coordinated Universal Time (UTC), local time, or tie in some other timezone is purely up to the program, just like it is up to the program, just like it is up to the program whether a particular number represents meters, miles, or mass.
  • Naive objects are easy to understand and to work with, at the cost of ignoring some aspects of reality.

Aware

  • An aware object has sufficient knowledge of applicable algorithmic and political time adjustments, such as time zone and daylight saving time information, to locate itself relative to other aware objects.
  • An aware object is used to represent a specific moment in time.
  • Objects of these types are immutable.
  • Objects of the data type are always naive.
  1. class datetime.date (An idealized naive date, assuming the current Gregorian calendar always was, and always will be, in effect. Attributes: year, month and day.)
  2. class datetime.time (An idealized time, independent of any particular day, assuming that every day has exactly 246060 seconds (there is no notion of “leap seconds” here.))
  3. class datetime.datetime (A combination of a date and a time, Attributes: year, month, day, hour, minute, second to microsecond and tzinfo.)
  4. class datetime.timedelta (An duration expressing the difference between two date, time, or datetime instances to microsecond resolution.)
  5. class datetime.tzinfo (An abstract base class for time zone information objects. These are used by the datetime and time classes to provide a customizable notion of time adjustment. ex- to account for time zone and/or daylight saving time).
  6. class datetime.timezone (A class that implements the tzinfo abstract base class as a fixed offset from the UTC.)

3. JSON

  • JavaScript Object Notation (JSON)
  • It’s a standard for information exchange.
  • JSON supports primitive types, like strings and numbers, as well as nested lists and objects.
  • JSON looks like a Python dictionary.
{
"firstName": "Jane",
"lastName": "Doe",
"hobbies": ["running", "sky diving", "Singing"],
"age": 35,
"children": [
{
"firstName" : "Bob",
"age" : 6
},
{
"firstName" : "Bob",
"age" : 8
}
]
}
  • Python comes with a built-in package called JSON for encoding and decoding JSON data
import json
  • The process of encoding JSON is usually called serialization. (Pickling)
  • Deserialization is the reciprocal process of decoding data that has been stored of delivered in the JSON standard (Depickiling)
  • method for writing data to files.
  • data object to be serialized
  • fp is a file-like object to which the bytes will be written.
import jsondata = {
"presidenr" : {
"name": "Zapod Beeblebrox",
"species": "Betelgeusian"
}
}

write_files = open("data_file.json", "w")
json.dump(data, write_files)
write_files.close()
  • method for writing to a python string.
json_string = json.dumps(data)
  • Turning JSON encoded data from a file into python objects.
import json
read_file = open("data_file.json", "r")
data = json.load(read_file)
  • Turning JSON encoded data from a string into python objects.
import json
json_string = """
{
"researcher": {
"name": "Ford Prefect",
"species": "Betelgeusian",
"relatives": [
{
"name": "Raphod Beeblebrox",
"species": "Betelgeusian"
}
]
}
}
"""

data = json.loads(json_string)

Thank You..

Data Scientist, Blockchain enthusiast, Entrepreneur.