0

Currently, I am trying to implement some exception handling class as like the Python in-built exception class. My Question is how python decide or choose which exception is occurred,

for example

Example 1 : (Integer/0) is always **ZeroDivisionError** Exception.
Example 2 : 'x' + 1 is always **TypeError** Exception.

How python catch that without using any Try and Except block.

For me i have to put my code inside some Try Block then put some Exception Name, which may not always be right because my Exception can hide ZeroDivision Exception as below :

>>> try:
...     1 / 0
... except Exception as e:
...     raise Exception (e)
...
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
Exception: integer division or modulo by zero
>>>

In my above code message is right but the exception name is wrong. So, someone please explain me how to write exception class and how to raise the right exception.

Thanks in adv.

3 Answers 3

1

By doing raise Exception (e), you are creating a new exception, of class Exception, and passing it the old one, e, as its argument. It will convert that argument to a string, so what you end up with is a plain old Exception instance, but with the message from a ZeroDivisionError.

If you want to raise an existing exception, just raise the exception itself:

raise e

However, if you're trying to re-raise the current exception, that's even easier:

raise

To answer your specific question:

My Question is how python decide or choose which exception is occurred,

In general, each function's implementation decides which exception to raise, but there are a few special cases that are explained in the appropriate parts of the language reference.

For your first example, in CPython, the int.__div__ method is implemented in C, but it effectively has code equivalent to this:

def __div__(self, other):
    if other == 0:
        raise ZeroDivisionError('integer division or modulo by zero')
    … do usual division stuff in C …

Your second example is one of those special cases: the implementation of the + operator asks str.__add__ to handle it, and that fails, so it then asks int.__radd__ to handle it, and that also fails, so it gives up and raises a TypeError.

Your third example… well, you explicit wrote raise Exception(e), and that raises an Exception.

Sign up to request clarification or add additional context in comments.

6 Comments

How can I decide which exception to catch ?
@yopy: If you want to catch a specific exception and not others, do that: except ZeroDivisionError as e:. If you want to catch any exception except for a few special cases, except Exception as e:. If you want to catch even those special cases, except BaseException as e:.
So python wrote a class called ZeroDivisionError exception somewhere right, so what that class is doing actually, just to print the exception argument as string with the exception name ?
Yes—and in fact, you can find that class in builtins and raise it yourself. See Built-in Exceptions for a list of the classes. Meanwhile, any exception class can define its own constructor, __str__, __repr__, etc. just like any other type, but most of them just inherit the default from the base (which, as you say, just prints the exception argument(s) as a string with the exception name).
See User-defined Exceptions in the tutorial if you want to know more about how to define useful exception classes.
|
1

raise without any argument reraise the same error.

>>> try:
...     1 / 0
... except Exception as e:
...     raise # <----
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: integer division or modulo by zero

Comments

1

Using Python 2.7, try raising e without casting it to Exception:

try:
    1 / 0
except Exception as e:
    raise e

Traceback (most recent call last):
  File "E:\Proyectos\Eclipse\Python\Test\__init__.py", line 4, in <module>
    raise e
ZeroDivisionError: integer division or modulo by zero

Edit: As @abarnet commented (see comment below), it is generally more recommended to raise rather than raise e.

1 Comment

It's generally better to raise here than raise e. The documentation doesn't really explain why, but an implementation can often re-raise the current exception more efficiently, and in some cases it preserves more under-the-covers information (that you usually won't see, but can dig up in the debugger).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.