0

I'm trying to just execute this simple exceptiion handler and it won't work for some reason. I want it to throw the exception and write the error to a file.

fileo = "C:/Users/bgbesase/Documents/Brent/ParsePractice/out.txt"

g = 4
h = 6
try:
    if g > h:
        print 'Hey'
except Exception as e:
    f = open(fileo, 'w')
    f.truncate()
    f.write(e)
    f.close()
    print e

Any ideas what I am doing wrong?

1
  • 4
    You're not throwing an exception. Do you understand that exception handling code only executes when an exception occurs in the code mainline, either by your code throwing an exception, or by having an exception thrown by a method you call? Commented Jun 6, 2013 at 14:57

2 Answers 2

5

Your snippet is not supposed to raise any exceptions. Maybe you want to do something like

try:
    if g > h:
        print 'Hey'
    else:
        raise NotImplementedError('This condition is not handled here!')
except Exception as e:
    # ...

Another possibility is that you meant to say:

try:
    assert g > h
    print 'Hey!'
except AssertionError as e:
    # ...

The assert keyword basically behaves like a "fail-safe." If the condition is false, it will raise an AssertionError exception. It is often used to check preconditions for arguments to functions. (Say a value needs to be greater than zero for the function to make sense.)


Edit:

An exception is a sort of "signal" in your code that halts whatever your program was doing and finds it way to the nearest "exception handler." Whenever an exception occurs in your program, all execution immediately halts, and it tries to go to the nearest except: section of the code. If none exists, the program crashes. Try executing the following program:

print 'Hello. I will try doing a sum now.'
sum = 3 + 5
print 'This is the sum: ' + str(sum)
print 'Now I will do a division!'
quotient = 5/0
print 'This is the result of that: ' + str(quotient)

If you run it, you will see that your program crashes. My Python tells me:

ZeroDivisionError: integer division or modulo by zero

This is an exception! Something exceptional happened! You can't divide by zero, of course. As you now know, this exception is a sort of signal that finds its way to the closest exception: block, or the exception handler. We can rewrite this program so it is safer.

try:
    print 'Hello. I will try doing a sum now.'
    sum = 3 + 5
    print 'This is the sum: ' + str(sum)
    print 'Now I will do a division!'
    quotient = 5/0
    print 'This is the result of that: ' + str(quotient)
except Exception as e:
    print 'Something exceptional occurred!'
    print e

Now we catch the exception, the signal that something exceptional happened. We put the signal in the variable e and we print it. Now your program will result in

Something exceptional occurred!
integer division or modulo by zero

When the ZeroDivisionError exception occurred, it stopped the execution at that spot, and went straight to the exception handler. We can also manually raise exceptions if we want to.

try:
    print 'This you will see'
    raise Exception('i broke your code')
    print 'This you will not'
except Exception as e:
    print 'But this you will. And this is the exception that occurred:'
    print e

The raise keyword manually sends an exception signal. There are different kinds of exceptions, like the ZeroDivisionError exception, the AssertionError exception, the NotImplementedError exception and tons more, but I leave those for further studies.

In your original code, there was nothing exceptional happening, so that's why you never saw an exception getting triggered. If you want to trigger an exception based on a condition (like g > h) you can use the assert keyword, which behaves a little like raise, but it only raises an exception when the condition is false. So if you write

try:
    print 'Is all going well?'
    assert 3 > 5
    print 'Apparently so!'
except AssertionError as e:
    print 'Nope, it does not!'

You will never see the "Apparently so!" message, since the assertion is false and it triggers an exception. Assertion are useful for making sure values make sense in your program and you want to abort the current operation if they don't.

(Note that I caught explicitly the AssertionError in my exception handling code. This will not catch other exceptions, only AssertionErrors. You'll get to this in no time if you continue reading about exceptions. Don't worry too much about them now.)

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

3 Comments

Since I'm all confused now, all I want to do is just print e to a file so I can see what it is, I thought I was close but I'm way off haha. :(
You need to generate e first. Your code raises no exceptions, so no exceptions are caught.
bbesase, I accidentally edited my post a little. See if it makes anything more clear.
3

You're not actually ever raising an exception. To raise an exception, you need to use the raise keyword with an Exception class or instance of an Exception class. In this case, I would recommend a ValueError as you've gotten a bad value.

fileo = "C:/Users/bgbesase/Documents/Brent/ParsePractice/out.txt"

g = 4
h = 6
try:
    if g > h:
        raise ValueError('Hey')
except Exception as e:
    f = open(fileo, 'w')
    f.truncate()
    f.write(str(e))
    f.close()
    print e

4 Comments

Ok, that makes sense. But I have now changed my code to be yours and it still isn't working correctly. Do I have to have an Exception class everytime?
The exception is never getting raised because the condition g > h isn't True (h > g)
I know g > h isnt' true, I want to see what e is and print it to a file that's why I made it false
@bbesase -- e is an exception instance.

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.