Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to catch TypeError Exception in Python?

In this code, I get an error , How to handle this exception and know its type?
Manogna
Answered on 6th Dec, 2017

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

How to catch IndentationError Exception in python?

The following code throws an error , How to handle this exception and know its type?
Manogna
Answered on 6th Dec, 2017

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

How to catch ZeroDivisionError Exception in Python?

If the following line of code is run at the python interpreter, I get an error. , How to catch this error and know the type of error?
Rajendra Dharmkar
Answered on 6th Dec, 2017

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

How to catch FloatingPointError Exception in Python?

When the code given below is run, I get an error. , How do I catch this error and know its type?
Rajendra Dharmkar
Answered on 6th Dec, 2017

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

How to catch StandardError Exception in Python?

In following code, I get an error , How can I catch this exception and know its type?
Rajendra Dharmkar
Answered on 6th Dec, 2017

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

How to catch StopIteration Exception in Python?

In the following code, I am getting an error , How do I catch this error and know its type?
Rajendra Dharmkar
Answered on 6th Dec, 2017

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

How to catch SystemExit Exception in Python?

I am trying to handle SystemExit Exception in the following manner , However, it does not work How do I handle the SystemExit Exception?
Rajendra Dharmkar
Answered on 6th Dec, 2017

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

How to catch ImportError Exception in Python?

If I run this line of code, I get an error , or if I run the following code also, I get an error , How do I catch such exceptions and know their types?
Rajendra Dharmkar
Answered on 6th Dec, 2017

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

How to catch NotImplementedError Exception in Python?

 NotImplementedError is derived from RuntimeError. Which methods should raise this exception when they require derived classes to override the method in user defined classes?.
Rajendra Dharmkar
Answered on 6th Dec, 2017

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

How to catch OSError Exception in Python?

When following code is run, I get error , How do I handle this error and know it type?
Rajendra Dharmkar
Answered on 6th Dec, 2017

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

How to handle Python exception in Threads?

In the code given below, a thread is started. The thread waits for few seconds and checks for an event and if it is found, it stops, else an Exception is thrown. I want to catch this Exception .....
Rajendra Dharmkar
Answered on 6th Dec, 2017

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

How to rethrow Python exception with new type?

I have the following code and I want to rethrow the exception with new type , except Exception as e:
Rajendra Dharmkar
Answered on 6th Dec, 2017

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

How to handle invalid arguments with argparse in Python?

I use argparse to parse command line arguments and by default on receiving invalid arguments it prints help message and exits.  ,  How to catch this exception when it receives invalid.....
Rajendra Dharmkar
Answered on 6th Dec, 2017

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

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

For the following code , how do I write a try/except block that catches all exceptions?
Manogna
Answered on 6th Dec, 2017

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

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

I would like to know if it is possible in python to raise an exception in one except block and catch it in a later except block. I have tried to implement this in code below, however it is not.....
Manogna
Answered on 6th Dec, 2017

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

Advertisements
Loading...
Unanswered Questions View All

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.