Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 5970483
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T20:22:50+00:00 2026-05-22T20:22:50+00:00

class AppError(Exception): pass class MissingInputError(AppError): pass class ValidationError(AppError): pass … def validate(self): """ Validate

  • 0
class AppError(Exception):
    pass

class MissingInputError(AppError):
    pass

class ValidationError(AppError):
    pass

…

def validate(self):
    """ Validate Input and save it """

    params = self.__params

    if 'key' in params:
        self.__validateKey(escape(params['key'][0]))
    else:
        raise MissingInputError

    if 'svc' in params:
        self.__validateService(escape(params['svc'][0]))
    else:
        raise MissingInputError

    if 'dt' in params:
        self.__validateDate(escape(params['dt'][0]))
    else:
        raise MissingInputError


def __validateMulti(self, m):
    """ Validate Multiple Days Request"""

    if m not in Input.__validDays:
        raise ValidationError

    self.__dCast = int(m)

validate() and __validateMulti() are methods of a class that validates and store the passed input parameters. As is evident in the code, I raise some custom exceptions when some input parameter is missing or some validation fails.

I’d like to define some custom error codes and error messages specific to my app like,

Error 1100: "Key parameter not found. Please verify your input."

Error 1101: "Date parameter not found. Please verify your input"

…

Error 2100: "Multiple Day parameter is not valid. Accepted values are 2, 5 and 7."

and report the same to the user.

  1. How do I define these error codes and error messages in the custom exceptions?
  2. How do I raise / trap exception in a way that I know what error code / message to display?

(P.S: This is for Python 2.4.3).


Bastien Léonard mentions in this SO comment that you don’t need to always define a new __init__ or __str__; by default, arguments will be placed in self.args and they will be printed by __str__.

Thus, the solution I prefer:

class AppError(Exception): pass

class MissingInputError(AppError):
    
    # define the error codes & messages here
    em = {1101: "Some error here. Please verify.", \
          1102: "Another here. Please verify.", \
          1103: "One more here. Please verify.", \
          1104: "That was idiotic. Please verify."}

Usage:

try:
    # do something here that calls
    # raise MissingInputError(1101)

except MissingInputError, e
    print "%d: %s" % (e.args[0], e.em[e.args[0]])
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T20:22:50+00:00Added an answer on May 22, 2026 at 8:22 pm

    Here’s a quick example of a custom Exception class with special codes:

    class ErrorWithCode(Exception):
        def __init__(self, code):
            self.code = code
        def __str__(self):
            return repr(self.code)
    
    try:
        raise ErrorWithCode(1000)
    except ErrorWithCode as e:
        print("Received error with code:", e.code)
    

    Since you were asking about how to use args here’s an additional example…

    class ErrorWithArgs(Exception):
        def __init__(self, *args):
            # *args is used to get a list of the parameters passed in
            self.args = [a for a in args]
    
    try:
        raise ErrorWithArgs(1, "text", "some more text")
    except ErrorWithArgs as e:
        print("%d: %s - %s" % (e.args[0], e.args[1], e.args[2]))
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

class AppError(Exception): pass class MissingInputError(AppError): em = {1101: Date input is missing. Please verify.,
class Ball: a = [] def __init__(self): pass def add(self,thing): self.a.append(thing) def size(self): print
class Foo { static bool Bar(Stream^ stream); }; class FooWrapper { bool Bar(LPCWSTR szUnicodeString)
class Tag(models.Model): name = models.CharField(maxlength=100) class Blog(models.Model): name = models.CharField(maxlength=100) tags = models.ManyToManyField(Tag) Simple
class A : IFoo { } ... A[] arrayOfA = new A[10]; if(arrayOfA is
class someclass {}; class base { int a; int *pint; someclass objsomeclass; someclass* psomeclass;
class Foo(models.Model): title = models.CharField(max_length=20) slug = models.SlugField() Is there a built-in way to
class AbstractQuery { virtual bool isCanBeExecuted()=0; public: AbstractQuery() {} virtual bool Execute()=0; }; class
class C { T a; public: C(T a): a(a) {;} }; Is it legal?
class Score { var $score; var $name; var $dept; var $date; function Score($score, $name,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.