Found 27104 Articles for Server Side Programming

How to catch an exception while using a Python 'with' statement?

Manogna
Updated on 27-Sep-2019 11:25:28

64 Views

The code can be rewritten to catch the exception as follows:try:      with open("myFile.txt") as f:           print(f.readlines()) except:     print('No such file or directory')We get the following outputC:/Users/TutorialsPoint1/~.py No such file or directory

How to catch a thread's exception in the caller thread in Python?

Manogna
Updated on 27-Sep-2019 11:26:40

514 Views

The problem is that thread_obj.start() returns immediately. The child thread that you started executes in its own context, in its own stack. Any exception that occurs there is in the context of the child thread. You have to communicate this information to the parent thread by passing some message.The code can be re-written as follows:import sys import threading import Queue class ExcThread(threading.Thread): def __init__(self, foo): threading.Thread.__init__(self) self.foo = foo def run(self): try: raise Exception('An error occurred here.') except Exception: self.foo.put(sys.exc_info()) def main(): foo = Queue.Queue() thread_obj = ExcThread(foo) thread_obj.start() while True: try: exc = foo.get(block=False) except Queue.Empty: pass else: exc_type, ... Read More

How to raise an exception in one except block and catch it in a later except block in Python?

Manogna
Updated on 27-Sep-2019 11:27:53

215 Views

Only a single except clause in a try block is invoked. If you want the exception to be caught higher up then you will need to use nested try blocks.Let us write 2 try...except blocks like this:try: try: 1/0 except ArithmeticError as e: if str(e) == "Zero division": print ("thumbs up") else: raise except Exception as err: print ("thumbs down") raise errwe get the following outputthumbs down Traceback (most recent call last): File "C:/Users/TutorialsPoint1/~.py", line 11, in raise err File "C:/Users/TutorialsPoint1/~.py", line 3, in 1/0 ZeroDivisionError: division by zeroAs per python tutorial there is one and only one ... Read More

How can I write a try/except block that catches all Python exceptions?

Manogna
Updated on 27-Sep-2019 11:29:24

145 Views

It is a general thumb rule that though you can catch all exceptions using code like below, you shouldn’t:try:     #do_something() except:     print "Exception Caught!"However, this will also catch exceptions like KeyboardInterrupt we may not be interested in. Unless you re-raise the exception right away – we will not be able to catch the exceptions:try:     f = open('file.txt')     s = f.readline()     i = int(s.strip()) except IOError as (errno, strerror):     print "I/O error({0}): {1}".format(errno, strerror) except ValueError:     print "Could not convert data to an integer." except:     ... Read More

How to handle invalid arguments with argparse in Python?

Rajendra Dharmkar
Updated on 10-Aug-2023 21:09:39

1K+ Views

Argparse is a Python module used to create user-friendly command-line interfaces by defining program arguments, their types, default values, and help messages. The module can handle different argument types and allows creating subcommands with their own sets of arguments. Argparse generates a help message that displays available options and how to use them, and it raises an error if invalid arguments are entered. Overall, argparse simplifies the creation of robust command-line interfaces for Python programs. Using try and except blocks One way to handle invalid arguments with argparse is to use try and except blocks. Example In this code, ... Read More

How to rethrow Python exception with new type?

Rajendra Dharmkar
Updated on 27-Sep-2019 11:33:50

152 Views

In Python 3.x, the code is subject to exception chaining and we get the output as followsC:/Users/TutorialsPoint1/~.py Traceback (most recent call last): File "C:/Users/TutorialsPoint1/~.py", line 2, in 1/0 ZeroDivisionError: division by zeroThe above exception was the direct cause of the following exception:Traceback (most recent call last): File "C:/Users/TutorialsPoint1/~.py", line 4, in raise ValueError ( "Sweet n Sour grapes" ) from e ValueError: Sweet n Sour grapes

How to handle Python exception in Threads?

Rajendra Dharmkar
Updated on 27-Sep-2019 11:35:03

1K+ Views

The given code is rewritten to catch the exceptionimport sys import threading import time import Queue def thread(args1, stop_event, queue_obj): print "start thread" stop_event.wait(12) if not stop_event.is_set(): try: raise Exception("boom!") except Exception: queue_obj.put(sys.exc_info()) pass try: queue_obj = Queue.Queue() t_stop = threading.Event() t = threading.Thread(target=thread, args=(1, t_stop, queue_obj)) t.start() time.sleep(15) print "stop thread!" t_stop.set() try: exc = queue_obj.get(block=False) except Queue.Empty: pass else: exc_type, exc_obj, exc_trace = exc print exc_obj except Exception as e: print "It took too long"OUTPUTC:/Users/TutorialsPoint1/~.py start thread stop thread! boom!Read More

How to catch OSError Exception in Python?

Rajendra Dharmkar
Updated on 27-Sep-2019 11:36:21

628 Views

OSError serves as the error class for the os module, and is raised when an error comes back from an os-specific function.We can re-write the given code as follows to handle the exception and know its type.#foobar.py import os import sys try: for i in range(5): print i, os.ttyname(i) except Exception as e: print e print sys.exc_typeIf we run this script at linux terminal$ python foobar.pyWe get the following outputOUTPUT0 /dev/pts/0 1 /dev/pts/0 2 /dev/pts/0 3 [Errno 9] Bad file descriptor

How to catch NotImplementedError Exception in Python?

Rajendra Dharmkar
Updated on 12-Feb-2020 10:36:48

1K+ Views

User-defined base classes can raise NotImplementedError to indicate that a method or behavior needs to be defined by a subclass, simulating an interface. This exception is derived from RuntimeError. In user defined base classes, abstract methods should raise this exception when they require derived classes to override the method.Exampleimport sys try:    class Super(object):         @property         def example(self):             raise NotImplementedError("Subclasses should implement this!")    s = Super()    print s.example except Exception as e:     print e     print sys.exc_typeOutputSubclasses should implement this!

How to catch ImportError Exception in Python?

Rajendra Dharmkar
Updated on 12-Jun-2020 07:42:03

3K+ Views

ImportError is raised when a module, or member of a module, cannot be imported. There are a two conditions where an ImportError might be raised.If a module does not exist.Exampleimport sys try:     from exception import myexception except Exception as e:     print e     print sys.exc_typeOutputNo module named exception If from X import Y is used and Y cannot be found inside the module X, an ImportError is raised.Example import sys  try:     from time import datetime  except Exception as e:     print e     print sys.exc_typeOUTPUT cannot import name datetime

Advertisements