Found 34423 Articles for Programming

How to capture and print Python exception message?

Rajendra Dharmkar
Updated on 12-Feb-2020 11:02:12

2K+ Views

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

120 Views

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

165 Views

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

348 Views

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

How do I manually throw/raise an exception in Python?

Rajendra Dharmkar
Updated on 12-Feb-2020 11:04:46

193 Views

We use the most specific exception constructor that fits our specific issue rather than raise generic exceptions. To catch our specific exception, we'll have to catch all other more specific exceptions that subclass it.We should raise specific exceptions and handle the same specific exceptions.To raise the specific exceptions we use the raise statement as follows.Exampleimport sys try: f = float('Tutorialspoint') print f raise ValueError except Exception as err: print sys.exc_info()outputWe get the following output(, ValueError('could not convert string to float: Tutorialspoint', ), )We can raise an error even with arguments like the following exampleExampletry: raise ValueError('foo', 23) except ValueError, e: ... Read More

Is there a standard way of using exception chains in Python 3?

Rajendra Dharmkar
Updated on 27-Sep-2019 10:47:31

232 Views

During the handling of one exception ‘A’, it is possible that another exception ‘B’ may occur. In Python 2.0 versions, if this happens, exception B is propagated outward and exception A is lost. It is useful to know about both exceptions in order to debug the problem.Sometimes it is useful for an exception handler to deliberately re-raise an exception, either to provide extra information or to translate an exception to another type. The __cause__ attribute provides an explicit way to record the direct cause of an exception.Exception chaining is only available in Python 3.  Python 3 has the raise ... ... Read More

Explain Try, Except and Else statement in Python.

Rajendra Dharmkar
Updated on 12-Feb-2020 11:17:53

949 Views

The common method to handle exceptions in python is using the "try-except" block. We can even include an else clause after except clause. The statements in the else block are executed if there is no exception in the try statement.The optional else clause is executed if and when control flows off the end of the try clause except in the case of an exception or the execution of a return, continue, or break statement.ExampleThe given code can be rewritten as followsa = [11, 8, 9, 2] try: foo = a[3] except: print "index out of range" else: print "index well ... Read More

How to use the ‘except clause’ with No Exceptions in Python?

Rajendra Dharmkar
Updated on 12-Feb-2020 11:21:05

2K+ Views

If we define except clause with no exceptions, it can handle all types of exceptions. However, neither it’s a good coding practice nor it is recommended.Exampletry: print 'foo'+'qux'+ 7 except: print' There is error'OutputYou get the outputThere is errorThis type of Python try-except block can handle all types of exceptions, but it’ll not be helpful to the programmer to find which type of exception occurred.

How do you properly ignore Exceptions in Python?

Rajendra Dharmkar
Updated on 27-Sep-2019 07:10:07

522 Views

This can be done by following codestry: x, y =7, 0 z = x/y except: passORtry: x, y =7, 0 z = x/y except Exception: passThese codes bypass the exception in the try statement and ignore the except clause and don’t raise any exception.The difference in the above codes is that the first one will also catch KeyboardInterrupt, SystemExit etc, which are derived directly from exceptions.BaseException, not exceptions.Exception.It is known that the last thrown exception is remembered in Python, some of the objects involved in the exception-throwing statement are kept live until the next exception. We might want to do ... Read More

How to use the ‘except’ clause with multiple exceptions in Python?

Manogna
Updated on 27-Sep-2019 10:51:43

3K+ Views

It is possible to define multiple exceptions with the same except clause. It means that if the Python interpreter finds a matching exception, then it’ll execute the code written under except clause.In general, the syntax for multiple exceptions is as followsExcept(Exception1, Exception2, …ExceptionN) as e:When we define except clause in this way, we expect the same code to throw different exceptions. Also, we want to take the action in each case.Example codeimport sys try: d = 8 d = d + '5' except(TypeError, SyntaxError)as e: print sys.exc_info()We get output as shown(, TypeError("unsupported operand type(s) for  +: 'int' and 'str'", ), ... Read More

Advertisements