Posts

Showing posts from December, 2018

Custom Exception in Python

Image
Concept When an error occurs, or exception as we call it, Python will normally stop and generate an error message But this is not expected in Real Life Application, So these exceptions can be handled using the  try, except  statement. Code Example 1: x = 10 if x == 10:   raise ValueError elif x == 20:   raise KeyboardInterrupt elif x == 30:   raise Exception("My Choice") else:   print("All Okay")   Output:  Traceback (most recent call last): File "./prog.py", line 4, in ValueError Quiz Level 1 Quiz Level 2 Request Me

Exception Handling In Python

Image
   Concept When an error occurs, or exception as we call it, Python will normally stop and generate an error message But this is not expected in Real Life Application, So these exceptions can be handled using the  try, except  statement. Code Example As we all know,  0/n = 0 and n/0 = ∞ Example 1: try:     result = 0/10     print("All Good") except Exception as e:     result  = 0     print("An exception occurred : ", e) else:     print("No Exception Occurred") finally:     print("Result is : ", result)   Output : All Good No Exception Occurred Result is : 0   Example 2: try:     result = 0/10     print("All Good") except Exception as e:     result  = 0     print("An exception occurred : ", e) else:     print("No Exception Occurred") finally:     print("Result is : ", result)   Output:  An exception occurred :  division by zero Result is : 0   Note**:  If try executed successfully then only else block will

Multithreading in Python

Image
  Code I n computer architecture, multithreading is the ability of a central processing unit to provide multiple threads of execution concurrently, supported by the operating system. This approach differs from multiprocessing. Multitasking is of two types: Processor-based and thread-based. Processor-based multitasking is totally managed by the OS, however multitasking through multithreading can be controlled by the programmer to some extent. The concept of  multi-threading  needs a proper understanding of these two terms –  a process and a thread . A process is a program being executed. A process can be further divided into independent units known as threads. A thread is like a small light-weight process within a process. Or we can say a collection of threads is what is known as a process. import logging import threading import time def thread_function1(name):     print("Thread {}: starting \n".format(name))     time.sleep(5)     print("Thread {}: finishing \n".form