Defining own exception

Hi,
I need to create an exception that will be thrown if a call to function x returns a negative value. I assume that means I need to create my own exception class. However, everything I've read about creating one's own exception class involves merely changing the text thrown by a given exception. How does one actually define an exception which says "Throw this when x is a particular value"?
Any suggestions?
Cheers,
Didje

You detect the fault yourself, and throw it. Eg
public class NegativeException extends Exception {
   public NegativeException() {
     super("negative number");
// in code elsewhere
if ( getValue() < 0 ) throw new NegativeException();

Similar Messages

  • N00b query: Why would anyone ever want to define their own Exception class?

    I've been reading thru my Java textbook for the past couple hours.
    Exceptions are a wonderful thing. I already found several instances where I could've implemented try/cacth in my earlier programs.
    Anyway, getting back to the point. My question is, can someone give me a realistic situation/example where a custom Expcetion class is REQUIRED? (the key word here is "required"!)
    I can see why someone would want to have his own Exception class..... e.getMessage() as custom error messages are SO DAMN COOL!!!!!! :P
    hehe
    But seriously, if you are making intermidiate/advanced Java programs, would you ever REQUIRE to make your own Exception class? Afterall, even a custom made Exception class always "extends" from a pre-defined Java class, right?
    Let me make this a bit more clear... public class CustomException extends IOException{  }Now, if I am making a try/catch statement, I can simply say
    try{
    throw new CustomException;
    catch (IOException e) { }
    Now as you can see, the CustomException was caught by the catch claus, because IOException is the superclass of CustomException. So, in other words, the whole CustomException thingy didnt do anything useful.
    I know I know, I am so naive. Enlighten me >.<

    Sure. Say you want to have a system where you want to include a custom error code which maps to some internationalized error messages. You would create an Exception subclass with a field to hold that value separate from the normal "default" message. Then you could throw that exception in all your code. Other code can catch it as a plain Exception if they want and use the "default" message, which is okay if they don't really care about the error code.
    I don't think you are ever "required" to make your own exceptions. I have done so, but I don't often. It depends. See, there are plenty of Exception subclasses in the standard packages, and most of them cover many of the things you need. So more often if I'm throwing an exception, I'll be using the already existing ones, like IllegalArgumentException or IOException (whatever is relevant to the code).
    Yes, you can do what you did below with CustomException. However the reason you might do that is cuz you really want to do this:
    try {
       // call some code that may throw IOException from some standard IO package
       // or may throw CustomException from some of my methods...
    } catch (CustomException ce) {
       // handle cusotm exception
    } catch (IOException ioe) {
       // handle IO exception
    }Cuz you may want to differentiate between your exceptions vs. IOExceptions that might be thrown from some java.io class.
    Usually when you use an exception class it's a named class that relates to some condition. It may hold additional information besides the standard message, but I think most of the time it's just the class name which describes the problem. And if there isn't one that describes the problem that you're code might encounter, then create a subclass.

  • Define our own Exceptions in th function builder

    hi
    how to define our own Exceptions in th function builder in the Exception tab and how to use them in functon definiton.
    regards
    ravish

    Hi,
    <b>Exceptions</b>
    The exception of a function module are defined on the Exceptions tab page in the Function Builder. Here you can select exception classes to define whether class-based exceptions are declared or non-class-based exception are defined. Class-based exceptions are represented in the above syntax by RAISING, and non-class-based exceptions are represented by EXCEPTIONS.
    The addition RAISING is used to declare class-based exceptions that can be propagated from the function module to the caller. Exceptions in the categories CX_STATIC_CHECK and CX_DYNAMIC_CHECK must be explicitly declared, otherwise a propagation can lead to an interface violation. A violation of the interface leads to the treatable exception CX_SY_NO_HANDLER. Exceptions of the category CX_NO_CHECK are implicitly always declared. The declaration of exceptions of the category CX_STATIC_CHECK is statically checked in the syntax check. For exceptions of the category CX_DYNAMIC_CHECK, the check is not performed until runtime. In a function module in which class-based exceptions are declared with the RAISING addition, the statement CATCH SYSTEM-EXCEPTIONS cannot be used. Instead, the relevant treatable exceptions should be handled in a TRY control structure.
    The addition EXCEPTIONS is used to define a list of non-class-based exceptions that can be triggered in the function module using the statements RAISE or MESSAGE RAISING. Exceptions defined in this way - as with formal parameters - are bound to the function module and cannot be propagated. If an exception of this type is triggered in a function module, and no return value has been assigned to it with the homonymous addition EXCEPTIONS of the CALL FUNCTION statement when the call was made, this leads to a runtime error.
    <b>Note</b>
    For new developments after release 6.10, SAP recommends that you work with class-based exceptions that are independent of the function module.
    Regards,
    Padmam.<b></b>

  • How can I define a own exception

    Hallo,
    I want to delete rows in a table after pressing the "Delete"-Button.
    When pressing "delete" the message box htmldb_delete_message is shown.
    When pressing "Ok" the row will not deleted if there are depending rows in another table. On the Form the Error "ORA-02292: Integritäts-Constraint (EV_ADM.SEM_TEILNAHME_PN_FK) verletzt - untergeordneter Datensatz gefunden" is displayed. For this ORA--message I want to create a own exception and displays a message that the user can understand. How can I do this?
    Thanks, Daniela

    See also
    how to avoid ora-errors to be displayed
    for a similar discussion, and a solution. Follow also the links in teh posts !
    Leo

  • Creating own Exception class

    In my past paper it says...
    Show how to create your own Exception class that derives from class Exception. The class should provide a default constructor which allows a "My Error message" message to be set, and a second constructor which has as an argument the error message. 4-MARKS
    Does this look right..?
    public class MyExcep extends Exception
         public MyExcep()
              super("My Error Message");
         public MyExcep(String message)
              super(message);
    }

    Yes. Do I get 4 marks now? or is it Four Marks?

  • "Non Defined IMS Exception" error while login on Presence Server

    Hi,
    I am getting "Non Defined IMS Exception" error while login on Presnce Server. I have configured Publisher Presence server on VMware already and now configuring another presence server in other office for backup purpose. I have copied same VM image and installed in another office which are connected by MPLS. I am able to login on server by admin login (OS administration) but not for administration login.
    Please help.
    Regards,
    Kalshetty

    Hi Kalshetty,
    Please check the following link for this error, it applies to CUPS 8.x
    https://supportforums.cisco.com/document/109296/error-non-defined-ims-exception-cups-8x
    HTH
    Manish

  • Throwing my  own exception

    I'm trying to throw my own exception but can't seem to do it. the method i'm using has three different exceptions that i need to declare. Heres my code with one exception (not working of course):
         public static String ProcessUserInput(){          
              BufferedReader kbd = new BufferedReader(new InputStreamReader(System.in));
              String line = "";
              BlankException blanke = new BlankException blanke();
              try{
    line = kbd.readLine();
    catch (IOException ex)
    System.out.println( "Error reading keyboard input." );
    return line;
    I've tried to throw a new exception called BlankException but i get the following error message:
    '(' or '[' expected
    BlankException blanke = new BlankException blanke();
    How do i put three of my own exceptions in this piece of code?

    how do i do that if i have three exceptions in the one methodYou can declare your method to throw as many exceptions as you want.
    Example:public void method() throws CustomExceptionA, CustomExceptionB, CustomExceptionC {
        if (/* something goes wrong */) {
            throw new CustomExceptionA();
        try {
        catch(IOException ioEx) {
            throw new CustomExceptionB();
        catch(Exception ex) {
            throw new CustomExceptionC();
    }

  • Is it possible to define arbitrary Exceptions in BPEL?

    Hello,
    I want to build a BPEL process where the REJECT action of multiple workflows should be routed to the same exception handling code. I achieve this by throwing an exception (with arbitrary name) in the REJECT block.
    Note that this "Exception" serves only as a marker and is not something thrown by an operation, how can I define it as a constant in BPEL?
    In the examples I've seen so far, exceptions (or faults) are always associated with an operation, does it have to be this way, or can I define arbitrary exceptions and throw them like in Java?
    Many thanks in advance
    ZHU Jia

    You can not define a function inside of a MathScript Node, but only because it isn't necessary. The way custom functions work in MathScript is that they are saved in .m files located in paths in the MathScript path list. When the MathScript compiler receives a function that it doesn't recognize, then it searches for it in the path list, and upon finding it, compiles and loads the function. You can specify these search paths manually by going to File>>MathScript Preferences from the MathScript Window or dynamically by using the path() command within a script.
    To answer your original question, if you would like to create custom functions dynamically within a VI, then you can simply build your custom functions using strings and then save them to an ASCII file with the extension .m. You could either save the file to a path already in the MathScript path list or you could dynamically specify the path by passing the path into a MathScript Node as a string and by using the path() command at the beginning of your script to set it.
    Kind Regards,
    E. Sulzer
    Applications Engineer
    National Instruments

  • Doubt on Throwing own exceptions in java rmi?

    Hello,
    I am writing my own exception class and want to send exception object to the specific client.
    But, Exception class constructor only accept string.
    If I want to send both string and its corresponding error constant, how can I throw it.
    thank you.

    But, Exception class constructor only accept string.That is simply untrue. Have another look.

  • Defining own zoom in & out keyboard shortcuts

    I have been looking for a decent PDF viewer with tabs for awhile and have found Dioretsa. https://itunes.apple.com/us/app/dioretsa/id411422230?mt=12 It's pretty great for everything except I'm having problems with the keyboard shortcuts for zoom in and zoom out. I want the behavior to be the same as in most of my programs: [Command and =] for Zoom In and [Command and -] for Zoom Out, both WITHOUT having to use the Shift key.
    In the program the default Zoom In and Zoom Out shortcuts are shown in the picture below. They REQUIRE me to use [Command and Shift and =] and [Command and Shift and -] for zooming in.
    This annoyed me so I wanted to define my own keyboard shortcuts under Keyboard preferences:
    In Dioretsa, it now looks like this:
    Zoom In now works as expected, without needing Shift. However, for Zooming out it doesn't work! I still need to push Shift.
    I noticed how for Zoom Out the hypthen is BOLD here! In Keyboard Preferences it is not! Also you'll notice that there is no Shift key in the default Zoom Out shortcut in Diotretsa!
    This behavior is really bugging me! Can anyone help? I tried setting Zoom Out to [Command and 0] and this works fine without having to use shift!

    Richard Segedi wrote:
    Another thing you can try, if you aren't already aware of it, is to put the mouse cursor in whatever you wish to magnify, then hold down the Control key and scroll the mouse ball upwards. Do the same but scroll it downwards to reduce the screen image to normal size. This works on everything on the screen. Takes a little getting used to but I find it quick and handy for a fast look at something too small to see otherwise.
    Rick
    ya, thanks, already 'discovered' that one by accident...so many shortcuts to learn!!!

  • Can we define own short cut keys like shift+a  for check boxes

    Hi
    My problem is that on a specific form i have 30 check boxes with the labels like c1, c2 c3 ...
    The user wants as access key for every check box to rid of the mouse by checking all the items one by one.
    Oracle developer access key option does not solve this problem . Is there any function in oracle by which i can define my own short keys like shift+1 for 1 and shift+2 for 2 .....
    Waiting for reply.

    You can do this by using an ampersand (&) in front of the character in the Label.
    The ampersand will not show up in the label itself.
    For example, Print &Forms will define F as the shortcut. Print &Queue Manager will define Q as the shortcut.

  • Define own colors for charts in BW 3.0b, is it possible???

    <u><i><b>Referes to BW 3.0b</b></i></u>
    I have another short question concerning graphs.
    Bex gives a fixed set of optional colors for charts, however I need some other colors in order to fit with the given style guide.
    I know that it is possible to use a picture, however I am looking for a way in order to define my own colors for charts.
    Anybody got an idea?
    Greetings,

    The problem is that I do not have a color column....
    I can choose a color in the chart designer and I also get to the same option when using the wizard. <i>I am not sure if it is the right wizard as I have never used the wizard for chart editing before. How do you open the wizard to edit an already existing chart?</i>.
    In all the menus I can't find any place where I could add RGB. I have my RGB code and everything, I just need to enter it somewhere, so no external tools needed.

  • Need an example for defining own element

    Hi:
    Is there an example that shows how to define your own element
    and subclass the node factory so that the DOMParser can recognize
    your element?
    Thanks in advance.
    null

    Chadwick Chow (guest) wrote:
    : Hi:
    : Is there an example that shows how to define your own element
    : and subclass the node factory so that the DOMParser can
    recognize
    : your element?
    : Thanks in advance.
    There are none currently. Maybe another form member has one he
    would like to share.
    Oracle XML Team
    http://technet.oracle.com
    Oracle Technology Network
    null

  • Define own colors for charts?

    I have another short question concerning graphs.
    Bex gives a fixed set of optional colors for charts, however I need some other colors in order to fit with the given style guide.
    I know that it is possible to use a picture, however I am looking for a way in order to define my own colors for charts.
    Anybody got an idea?
    Greetings,
    Nana

    The problem is that I do not have a color column....
    I can choose a color in the chart designer and I also get to the same option when using the wizard. <i>I am not sure if it is the right wizard as I have never used the wizard for chart editing before. How do you open the wizard to edit an already existing chart?</i>.
    In all the menus I can't find any place where I could add RGB. I have my RGB code and everything, I just need to enter it somewhere, so no external tools needed.

  • Need help on creating my own exception class

    The program should check if the user entered a string larger than eight characters. If so, throw a user-defined exception. I'm getting the following errors:
    Any help is great.
    C:\Program Files\Xinox Software\JCreatorV3\MyProjects\StringTooLong\src\StringTooLong.java:25: <identifier> expected
    System.out.println("Enter a message less or equal of eight characters:\n:");
    ^
    C:\Program Files\Xinox Software\JCreatorV3\MyProjects\StringTooLong\src\StringTooLong.java:27: illegal start of type
    try
    ^
    C:\Program Files\Xinox Software\JCreatorV3\MyProjects\StringTooLong\src\StringTooLong.java:41: <identifier> expected
    ^
    3 errors
    import java.io.*;
    * The main logic class of the program.
    public class StringTooLong implements IOException
         BufferedReader br = new BufferedReader(new InputSTreamReader(System.in));
         String buffer = "";                    // Stores user input.
         // Tells the user what to do.
         System.out.println("Enter a message less or equal of eight characters:\n:");
         try
              buffer = br.readLine();
              if (buffer.length > 8)
                   throw new StringTooLongException;
              System.out.println("Your String: " + buffer);     
         catch (StringTooLongException e)
              System.out.println("\nThe string was too long!");
    class StringTooLongException extends Exception
         public StringTooLongException()
    }

    well you've mis-typed "InputStreamReader" (note capital t) and I don't think you want to be implementing IOException.
    Oh, and you're code isn't inside a method.
    Do this:public class WhateverItsCalled {
      public static void main(String[] args) throws IOException {
       // your code goes here
    // your other class here

Maybe you are looking for