TypeErrors are caused by combining the wrong type of objects, or calling a function with the wrong type of object.import sys try : ny = 'Statue of Liberty' my_list = [3, 4, 5, 8, 9] print my_list + ny except TypeError as e: print e print sys.exc_typeOUTPUTcan only concatenate list ... Read More
A IndentationError occurs any time the parser finds source code that does not follow indentation rules. We can catch it when importing a module, since the module will be compiled on first import. You can't catch it in the same module that contains the try/except block, because with this exception, ... Read More
When zero shows up in the denominator of a division operation, a ZeroDivisionError is raised.We re-write the given code as follows to handle the exception and find its type.import sys try: x = 11/0 print x except Exception as e: print sys.exc_type print eOUTPUT<type 'exceptions.ZeroDivisionError'> integer division or modulo by ... Read More
FloatingPointError is raised by floating point operations that result in errors, when floating point exception control (fpectl) is turned on. Enabling fpectl requires an interpreter compiled with the --with-fpectl flag.The given code is rewritten as follows to handle the exception and find its type.import sys import math import fpectl try: ... Read More
There is the Exception class, which is the base class for StopIteration, StandardError and Warning. All the standard errors are derived from StandardError. Some standard errors like ArithmeticErrror, AttributeError, AssertionError are derived from base class StandardError.When an attribute reference or assignment fails, AttributeError is raised. For example, when trying to ... Read More
When an iterator is done, it’s next method raises StopIteration. This exception is not considered an error.We re-write the given code as follows to catch the exception and know its type.import sys try: z = [5, 9, 7] i = iter(z) print i print i.next() print i.next() print i.next() print ... Read More
In python documentation, SystemExit is not a subclass of Exception class. BaseException class is the base class of SystemExit. So in given code, we replace the Exception with BaseException to make the code worktry: raise SystemExit except BaseException: print "It works!"OUTPUTIt works!The exception inherits from BaseException instead of StandardError or ... Read More
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.import sys try: from exception import myexception except Exception as e: print e print sys.exc_typeOUTPUTNo ... Read More
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.import sys ... Read More
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 ... Read More
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) ... Read More
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 <module> 1/0 ZeroDivisionError: division by zero The above exception was the direct cause of the following exception: Traceback (most recent call ... Read More
We rewrite given code as follows#foo.py import argparse class InvalidArgError(Exception):pass parser = argparse.ArgumentParser() parser.add_argument("echo") args = parser.parse_args() try: print (args.echo) raise InvalidArgError except InvalidArgError as e: print eWhen this script is run at the terminal as follows$ python foo.py echo barWe get the following outputusage: foo.py [-h] echo foo.py: error: ... Read More
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 ... Read More
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 ... Read More
We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy. Accept Learn more