- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Found 10784 Articles for Python
530 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
217 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
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
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
153 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
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
634 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
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!
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