Found 10533 Articles for Python

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

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

How to catch SystemExit Exception in Python?

Rajendra Dharmkar
Updated on 12-Feb-2020 10:39:46

2K+ Views

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 workExampletry: raise SystemExit except BaseException: print "It works!"OutputIt works!The exception inherits from BaseException instead of StandardError or Exception so that it is not accidentally caught by code that catches Exception.We would rather write the code this wayExampletry: raise SystemExit except SystemExit: print "It works!"OutputIt works!

How to catch StopIteration Exception in Python?

Rajendra Dharmkar
Updated on 12-Feb-2020 10:40:43

1K+ Views

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.Exampleimport sys try: z = [5, 9, 7] i = iter(z) print i print i.next() print i.next() print i.next() print i.next() except Exception as e: print e print sys.exc_type Output 5 9 7

How to catch StandardError Exception in Python?\\\

Rajendra Dharmkar
Updated on 12-Feb-2020 10:41:26

466 Views

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 reference an attribute that does not exist:We rewrite the given code and catch the exception and know it type.Exampleimport sys try: class Foobar: def __init__(self): self.p = 0 f = Foobar() print(f.p) print(f.q) except Exception as e: print e print sys.exc_type print 'This is an example of StandardError exception'Output0 Foobar ... Read More

How to catch FloatingPointError Exception in Python?

Rajendra Dharmkar
Updated on 12-Feb-2020 10:42:09

1K+ Views

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.Exampleimport sys import math import fpectl try: print 'Control off:', math.exp(700) fpectl.turnon_sigfpe() print 'Control on:', math.exp(1000) except Exception as e: print e print sys.exc_type OutputControl off: 1.01423205474e+304 Control on: in math_1

How to catch ZeroDivisionError Exception in Python?

Rajendra Dharmkar
Updated on 12-Feb-2020 10:42:53

500 Views

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.Exampleimport sys try: x = 11/0 print x except Exception as e: print sys.exc_type print eOutput integer division or modulo by zero

How to catch ValueError using Exception in Python?

Manogna
Updated on 12-Jun-2020 07:56:10

329 Views

A ValueError is used when a function receives a value that has the right type but an invalid value.The given code can be rewritten as follows to handle the exception and find its type.Exampleimport sys try: n = int('magnolia') except Exception as e: print e print sys.exc_typeOutputinvalid literal for int() with base 10: 'magnolia'

How to catch LookupError Exception in Python?

Manogna
Updated on 12-Feb-2020 10:54:12

2K+ Views

LookupError Exception is the Base class for errors raised when something can’t be found. The base class for the exceptions that are raised when a key or index used on a mapping or sequence is invalid: IndexError, KeyError.An IndexError is raised when a sequence reference is out of range.The given code is rewritten as follows to catch the exception and find its typeExampleimport sys try: foo = [a, s, d, f, g] print foo[5] except IndexError as e: print e print sys.exc_typeOutputC:/Users/TutorialsPoint1~.py list index out of range

How to catch EnvironmentError Exception in Python?

Manogna
Updated on 12-Feb-2020 10:53:26

462 Views

EnvironmentError is the base class for errors that come from outside of Python (the operating system, filesystem, etc.). EnvironmentError Exception is a subclass of the StandarError class. It is the base class for IOError and OSError exceptions. It is not actually raised unlike its subclass errors like IOError and OSError.Any example of an IOError or OSError should be an example of Environment Error as well.Exampleimport sys try: f = open ( "JohnDoe.txt", 'r' ) except Exception as e: print e print sys.exc_typeOutput[Errno 2] No such file or directory: 'JohnDoe.txt'

Advertisements