Found 10533 Articles for Python

How to write custom Python Exceptions with Error Codes and Error Messages?

Rajendra Dharmkar
Updated on 27-Sep-2019 11:23:45

985 Views

We can write custom exception classes with error codes and error messages as follows:class ErrorCode(Exception):     def __init__(self, code):         self.code = code     try:     raise ErrorCode(401) except ErrorCode as e:     print "Received error with code:", e.codeWe get outputC:/Users/TutorialsPoint1/~.py Received error with code: 401We can also write custom exceptions with arguments, error codes and error messages as follows:class ErrorArgs(Exception):     def __init__(self, *args):         self.args = [a for a in args] try:     raise ErrorArgs(403, "foo", "bar") except ErrorArgs as e:     print "%d: %s ... Read More

Suggest a cleaner way to handle Python exceptions?

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

164 Views

We can use the finally clause to clean up whether an exception is thrown or not:try:   #some code here except:   handle_exception() finally:   do_cleanup()If the cleanup is to be done in the event of an exception, we can code like this:should_cleanup = True try:   #some code here   should_cleanup = False except:   handle_exception() finally:   if should_cleanup():     do_cleanup()

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

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

107 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

751 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

267 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

195 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

2K+ 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

201 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

788 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

Advertisements