Found 9138 Questions for Python

How to catch ArithmeticError Exception in Python?

Rajendra Dharmkar
Updated on 12-Jun-2020 08:07:42
ArithmeticError Exception is the base class for all errors that occur for numeric calculations. It is the base class for those built-in exceptions like: OverflowError, ZeroDivisionError, FloatingPointErrorWe can catch the exception in given code as followsExampleimport sys try: 7/0 except ArithmeticError as e: print e print sys.exc_type print 'This is an example of catching ArithmeticError'Outputinteger division or modulo by zero This is an example of catching ArithmeticError

How to catch IOError Exception in Python?

Rajendra Dharmkar
Updated on 12-Jun-2020 08:08:32
IOError ExceptionIt is an error raised when an input/output operation fails, such as the print statement or the open() function when trying to open a file that does not exist. It is also raised for operating system-related errors.If the given code is written in a try block, it raises an input/output exception, which is handled in the except block as shown given belowExampleimport sys def whatever(): try: f = open ( "foo.txt", 'r' ) except IOError, e: print e print sys.exc_type whatever() Output[Errno 2] No such file or directory: 'foo.txt'

Where can I find good reference document on python exceptions?

Rajendra Dharmkar
Updated on 30-Jul-2019 22:30:20
The following link is a  good reference document on python exceptionshttps://docs.python.org/2/library/exceptions.html

How to get Python exception text?

Rajendra Dharmkar
Updated on 26-Sep-2019 20:03:49
If a python code throws an exception, we can catch it and print the type, the error message, traceback and get information like file name and line number in python script where the exception occurred.We can find the type, value, traceback parameters of the errorType gives the type of exception that has occurred; value contains error message; traceback contains stack snapshot and many other information details about the error message.The sys.exc_info() function returns a tuple of these three attributes, and the raise statement has a three-argument form accepting these three parts.Getting exception type, file number and line number in sample ... Read More

How will you explain that an exception is an object in Python?

Rajendra Dharmkar
Updated on 26-Sep-2019 20:04:17
Yes in given code ‘err’ is an exception object.In python everything is an object. And every object has attributes and methods. So exceptions much like lists, functions, tuples etc are also objects. So exceptions too have attributes like other objects. These attributes can be set and accessed as follows. There is the base class exception of which pretty much all other exceptions are subclasses. If e is an exception object, then e.args and e.message are its attributes.In current Python implementation, exceptions are composed of three parts: the type, the value, and the traceback. The sys module, describes the current exception ... Read More

How do you handle an exception thrown by an except clause in Python?

Rajendra Dharmkar
Updated on 12-Feb-2020 11:01:09
We have a scenario in which code in except clause itself raises exception. In given code, we can handle the exception raised by except clause as follows.Exampleimport sys try: a = john except: try: 4/0 except: print sys.exc_info() OutputWe get the following output"C:/Users/TutorialsPoint1/~.py" (, ZeroDivisionError('integer division or modulo by zero',), )

How to capture and print Python exception message?

Rajendra Dharmkar
Updated on 12-Feb-2020 11:02:12
Python exception messages can be captured and printed in different ways as shown in two code examples below. In the first one, we use the message attribute of the exception object.Exampletry: a = 7/0 print float(a) except BaseException as e: print e.messageOutputinteger division or modulo by zeroIn case of given code, we import the sys module and use the sys.exc_value attribute to capture and print the exception message.Exampleimport sys def catchEverything(): try: a = 'sequel' b = 0.8 print a + b except Exception as e: print sys.exc_value catchEverything()Outputcannot concatenate 'str' and 'float' objects

Why are Python exceptions named "Error" (e.g. ZeroDivisionError, NameError, TypeError)?

Rajendra Dharmkar
Updated on 30-Jul-2019 22:30:20
We see that most exceptions have their names ending in word ‘error’ pointing that they are errors which is the meaning of exceptions anyway.Errors in restricted sense are taken to mean syntax errors in python and those errors occurring at run time are called exceptions. As we know that classes do not have ‘class’ in their name; and similarly variables do not have names ending in ‘variable’ and so on. So there is no case that exceptions should have names ending in the word ‘exception’.Consider this; not all exceptions are errors. SystemExit, KeyboardInterrupt, StopIteration, GeneratorExit are all exceptions and not ... Read More

How to declare custom exceptions in modern Python?

Rajendra Dharmkar
Updated on 26-Sep-2019 20:13:52
To override something or pass extra arguments to the exception we do like this in modern python:class ValidationError(Exception): def __init__(self, message, errors): super(ValidationError, self).__init__(message) self.errors = errorsThat way we could pass dictionary of error messages to the second parameter, and get to it later on when needed.

What is the best way to log a Python exception?

Rajendra Dharmkar
Updated on 12-Feb-2020 11:03:39
We import the logging module and then use the logging.exception method to create a log of the python exception.Exampleimport logging try: print 'toy' + 6 except Exception as e: logging.exception("This is an exception log")OutputWe get the following outputERROR:root:This is an exception log Traceback (most recent call last): File "C:/Users/TutorialsPoint1/PycharmProjects/TProg/Exception handling/loggingerror1.py", line 3, in print 'toy' + 6 TypeError: cannot concatenate 'str' and 'int' objectsIt is noted that in Python 3 we must call the logging.exception method just inside the except part. If we call this method in any other place we may get a weird exception as per alert ... Read More
Advertisements