Alex Brodov
Alex Brodov

Reputation: 3515

Python 2.7 exception handling

I'm using python 2.7, I've build a custom exception class, and when i'm catching this exception the program doesn't stop.

Here is a snippet from my code:

try:
    result = OsUtils.is_os_name_valid(allowedSystems)
    print "This is the result: {0}".format(result)
    if result is False:
        raise ErrorUnsupportedOsSystemException(OsUtils.get_os_type())
except ErrorUnsupportedOsSystemException as e:
    print "({0}) {1}, ".format(e.os_type, e.message)
except IOError as e:
    print "I/O error ({0}) : {1}".format(e.errno, e.strerror)
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise
print "Test"

This is the exception class:

class ErrorUnsupportedOsSystemException(Exception):
    message = "Error: unsupported system!!"

    def __init__(self, os_type):
        self.os_type = os_type

    pass

Here is the output that i'm getting:

This is the result: False
(posix) Error: unsupported system!!, 
Test

The "Test" shouldn't been printed.

Upvotes: 1

Views: 719

Answers (1)

Andrew_CS
Andrew_CS

Reputation: 2562

Try something like this. Make it work with your code.

import sys

try:
    things...
except ErrorThatJustShouldBeLogged as e:
    log an error or something
except ErrorThatShouldExitProgram as e:
    sys.exit(0)

Upvotes: 1

Related Questions