Making Own Exception Class

Hi all,
I m trying to make a new exception class which will be called when when any sort of exception occurs.After throwing that class how can i call other exception in that class eg. if in a class if sqlexception occurs & i m throwing myclass so how can i catch sqlexception in myclass.

if in a class if sqlexception occurs & i m throwing myclass so how can i catch sqlexception in myclass.
you can throw your class object only when you catch the original exception. so pass the oroginal exception object in the constructor of your exception class.
hope you get what i mean.
- Azodious

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.

  • 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?

  • 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

  • Generated constructor in exception classes - ommitted textid in superclass

    Hi,
    debugging another program i stopped in the constructor of one of my own exception classes. Starring at the code one questoion arised
    method constructor.
    call method super->constructor
    exporting
    textid = textid
    previous = previous
    if textid is initial.
       me->textid = zcx_xi .
    endif.
    me->errortext = errortext .
    me->sysid = sysid .
    endmethod.
    First of all i would use
    if textid is *supplied*.
       me->textid = zcx_xi .
    endif.
    But this is not my question. If i'm raising this exception without supplying the textid the superclass is call with an initial textid, which is filled later pn with the predefined class named textid.
    If i'm raising this exception specifying the textid as
    raise exception type zcx_xi exporting textid = zcx_xi=>zcx_xi errortext = message.
    the super class will not get an intial textid but the predefined one.
    Both versions are working well delivering the errortext by the get_text( ) method in the catch branch.
    But... is there really no difference calling the super class with initial value or given value?

    It looks like there is no difference.
    This code replaces any existing TEXTID set by Super class when we don't pass any TEXTID.
    IF textid IS INITIAL.
       me->textid = CX_SY_ZERODIVIDE .
    ENDIF.
    If the code uses the attribute TEXTID (me->textid) instead of the importing parameter TEXTID, than it would make a lot difference.
    IF ME->textid IS INITIAL.   " Attribute TEXTID
       me->textid = CX_SY_ZERODIVIDE .
    ENDIF.
    I guess, we need some SAP Official response before going ahead.
    Regards,
    Naimesh Patel

  • 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();

  • 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.

  • Each exception class in its own file????

    Hi, I am still quite new to java, and I don't fully understand exceptions. Could you please tell me if for each exception class you require do you have to have a a seperate file. e.g. I'm creating my own array exceptions classes.
    The following is the structure:
    ** The base array exceptions class
    public class arrayException extends Exception {
    public arrayException () { super(); }
    public arrayException (String s) { super(s); }
    ** The outofboundsArrayException
    public class outofboundsArrayException extends arrayException {
    public outofboundsArrayException ()
    { super("Number entered is out of bounds"); }
    public outofboundsArrayException (String s)
    { super(s); }
    ** The fullArrayExceptiom
    public class fullArrayException extends arrayException {
    public fullArrayException ()
    { super("The array is full"); }
    public fullArrayException (String s)
    { super(s); }
    So will the three classes above need their own file.
    I wanted to also know what the super does. I thought when the exception was raised, the text message in the super method is outputted, but i've tested that and it doesn't output (e.g. the error message "The array is full" doesn't output). The only thing that outputs is what you put in the catch part.
    Thank You very Much!

    Could you please tell me if
    for each exception class you require do you have to
    have a a seperate file.Yes. Exception classes are like any other public class in Java, in that it must be in its own file with the standard naming conventions.
    I wanted to also know what the super does. I thought
    when the exception was raised, the text message in
    the super method is outputted, but i've tested that
    and it doesn't outputsuper([0,]...[n]) calls a constructor in the superclass of your current class matching the signature super([0,]...[n]). In this particular case, the Exception's message property is being set by the parent constructor. If you were to leave out super([0,]...[n]), the default no-arg constructor of the superclass would be invoked, and the message would not be set.
    Use the getMessage() method of the Exception class to return the message value in later references to your object.

  • Own ZCX Exception Class, how to translate

    Hi,
    i've written my own ZCX_XYZ exception class. On the tabstrip "Texts" i've entered some texts, but how can i translate those texts? When i'm going to Goto/Translations i'm just getting empty object list...

    Thanks for investigating again. Using SE63_OTR i'm getting the message that this is obsolet and i have to use SE63.
    To make things more clearer i made some screenshots.
    <a href="http://666kb.com/i/atri3x4ib1uryogzr.png">Class with Attributes</a>
    So i have a class ZCX_FTP, the superclass is CX_DYNAMIC_CHECK, and i have an attribut which was generated automatically with the same name of the class.
    The texts are as follows:
    <a href="http://666kb.com/i/atri6gk1z8qn3ff9j.png">Defined Text</a>
    So now i'm going to SE63 (BTW are these texts otr short texts or long ones?), entered the ID and pressed Edit:
    <a href="http://666kb.com/i/atri82j1b5x02q7ev.png">SE63 with ID</a>
    I'm getting Object does not exists....
    Logging on with different language might be a workaround with de/en, but i have some difficulties navigating inswedish, greek, france and half a dozen more languages. On the other hand, i do not want to hand over the source texts to those who translates the texts. I'm really lost in this and cant find online help/documentation dealing with this.

  • Does wscompile generate "fault" tag in WSDL file from Java exception class?

    I'm trying to generate WSDL files from Java classes. I defined some of my own exception that inherits from "RemoteException", but wscompile doesn't generate the corresponding complex type and "fault" tag. Does anyone know if this is a bug or wscompile doesn't support from Java Exception to fault?
    Thanks

    It will if the exceptions do not inherit from RemoteException.

  • Can we extend the Throwable class instead of Exception Class??

    Hi all..
    Can we extend the Throwable class instead of Exception Class while creating our own custom Exception?If not Why?
    Please give your valuble advices..
    Ramesh.

    I don't want to hijack the thread here, but in a conversational tone...on a related note.. I've thought about this too a bit and wondered if there are some recommended practices about catching and handling Throwable in certain applications. Like the other day I was debugging a web application that was triggering a 500. The only way I could find the problem in an error stack was to write code to catch Throwable, log the stack, and then re-throw it. I considered it "debug" code, and once I solved the problem I took the code out because, my understanding is, we don't want to be handling runtime problems... or do we? Should I have a catch clause for Throwable in my servlet and then pass the message to ServletException?
    So along with the OP question, are there separate defined occasions when we should or should not handle Throwable? Or does it just all depend on circumstance?

  • Create a Exception Class

    hi all ,,
    can any one tell me how to create a exception class in ABAP OOPS concept ??
    if possible can give link also for document

    HI Jayakumar,
    Please go thru this document
    Exceptions are represented by objects that are instances of exception classes. Defining an exception is, therefore, the same as creating an exception class.
    All exception classes must inherit from the common superclass CX_ROOT and one of its subordinate classes:
    CX_STATIC_CHECK
    CX_DYNAMIC_CHECK
    CX_NO_CHECK
    . The assignment of exception classes to one of these three paths of the inheritance hierarchy determines the way in which the associated exceptions are propagated. There is a record of predefined exception classes CX_SY_... whose exceptions are raised in error situations in the runtime environment. These classes all inherit from CX_DYNAMIC_CHECK or CX_NO_CHECK but not from CX_STATIC_CHECK (see hierarchy in the ABAP keyword documentation).
    All exception classes must begin with the prefix CX_. They are usually defined globally with the Class Builder of the ABAP Workbench. Local exception classes can, however, also be defined.
    Individual (abstract) exception classes that are used as the superclass of further exception classes can be defined. The exceptions of the subordinate classes can be handled together using a superclass.
    Exception classes have the following features:
    Constructor
    The constructor must have a predefined structure and a specific interface. With global classes, the Class Builder generates the correct constructor and sets it to an unchangeable status. The constructor has two IMPORTING parameters:
    TEXTID of the SOTR_CONC type
    This parameter can be used to determine which of your exception texts the exception will use.
    PREVIOUS of the CX_ROOT type
    This parameter can be used to assign the PREVIOUS attribute a previous exception.
    Methods
    In exception classes, you can define your own methods. The following two predefined methods are inherited from the root class CX_ROOT:
    GET_TEXT
    Sends back the exception texts of a class (controlled by the TEXTID attribute) as a string.
    GET_SOURCE_POSITION
    Returns the program name, the name of a possible include program, and the line number of the statement that raised the exception.
    Attributes
    The attributes of exception classes are used to transport additional information on an error situation to the handler. The main piece of information is, however, always the fact that an exception of a particular class has occurred. The following attributes are inherited from CX_ROOT:
    TEXTID
    Used to specify the exception of a class more precisely by using several exception texts. Is evaluated in the GET_TEXT method.
    PREVIOUS
    If an exception is mapped to another exception, a reference to the original exception can be defined in this attribute via the EXPORTING addition of the RAISE EXCEPTION statement and by means of the constructor IMPORTING PARAMETER with the same name. This can result in a chain of exception objects. In the event of a runtime error, the exception texts of all the exceptions in the chain are output. Mapping an exception to another exception is only beneficial if the context in which the original exception occurred is important for characterizing the error situation.
    KERNEL_ERRID
    The name of the associated runtime error is stored in this attribute if the exception was raised by the runtime environment, for example, COMPUTE_INT_ZERODIVIDE with a division by zero. If the exception is not handled, precisely this runtime error occurs.
    Parameters cannot be transferred to the constructor for this attribute. If the exception is raised with RAISE EXCEPTION, the attribute is set to initial.
    Global Exception Classes
    Global exception classes are defined and managed in the Class Builder. If the correct naming convention (prefix CX_) and the class type Exception Class is chosen when a new class is created, the Class Builder automatically becomes the Exception Builder.
    The Exception Builder offers precisely the functionality required to define exception classes and generates independently-defined components that must not be changed. When classes are created, the category of the exception must be specified, in other words, whether it is to inherit from CX_STATIC_CHECK, CX_DYNAMIC_CHECK, or CX_NOCHECK.
    Tab Pages of the Exception Builder
    The Exception Builder has the tab pages Properties, Attributes, Methods, and Texts.
    The properties do not normally need to be changed.
    Except for the four inherited attributes mentioned above, further public attributes can be generated by the Exception Builder. The contents of these attributes specify the exception more clearly and manage the exception texts.
    All of the methods are inherited from CX_ROOT. New methods cannot be added. The instance constructor is generated automatically. It ensures that, when an exception is raised, the attributes have the right values. It also transfers the text of the superclass for an exception class whose exception text is not specified explicitly.
    The instance constructor is generated on the basis of the attributes, which are set up on the basis of the exception texts. Changing the attributes in superclasses can, therefore, invalidate the constructors of subordinate classes. The constructors of subordinate classes can be regenerated under Utilities ® CleanUp ® Constructor.
    Texts are a special feature of exception classes and the Exception Builder. For further information, refer to Exception Texts.
    Local Exception Classes
    Local exception classes can be defined for specific exceptions that only occur within one single ABAP program. The condition for a local exception class is that it inherits from one of the three classes CX_STATIC_CHECK, CX_DYNAMIC_CHECK, or CX_NO_CHECK, or from their subordinate classes. An individual constructor and individual attributes can be created. Individual methods should not be created, however, and the methods of superclasses should not be redefined.
    Examples of Local Exception Classes
    report DEMO_LOCAL_EXCEPTION_1.
    class CX_LOCAL_EXCEPTION definition
                            inheriting from CX_STATIC_CHECK.
    endclass.
    start-of-selection.
        try.
          raise exception type CX_LOCAL_EXCEPTION.
        catch CX_LOCAL_EXCEPTION.
          message 'Local Exception!' type 'I'.
      endtry.
    This example shows a minimal local exception class, which is simply the local representation of one of the three direct subordinate classes of CX_ROOT. It can be used in the program.
    report DEMO_LOCAL_EXCEPTION_2.
    class CX_LOCAL_EXCEPTION definition
                            inheriting from CX_STATIC_CHECK.
      public section.
        data LOCAL_TEXT type STRING.
        methods CONSTRUCTOR importing TEXT type STRING.
    endclass.
    class CX_LOCAL_EXCEPTION implementation.
      method CONSTRUCTOR.
        SUPER->CONSTRUCTOR( ).
        LOCAL_TEXT = TEXT.
      endmethod.
    endclass.
    data OREF type ref to CX_LOCAL_EXCEPTION.
    start-of-selection.
        try.
          raise exception type CX_LOCAL_EXCEPTION
                          exporting TEXT = `Local Exception`.
        catch CX_LOCAL_EXCEPTION into OREF.
          message OREF->LOCAL_TEXT type 'I'.
      endtry.
    In this example, the exception class from the previous example is extended to include an individual attribute and constructor. The IMPORTING parameter of the constructor must be supplied when the exception is raised (it is required here). The attribute can be evaluated in the handler of the exception.
    report DEMO_LOCAL_EXCEPTION_3.
    class CX_LOCAL_EXCEPTION definition
          inheriting from CX_SY_ARITHMETIC_ERROR.
      public section.
        methods CONSTRUCTOR importing SITUATION type STRING.
    endclass.
    class CX_LOCAL_EXCEPTION implementation.
      method CONSTRUCTOR.
        SUPER->CONSTRUCTOR( OPERATION = SITUATION ).
      endmethod.
    endclass.
    data OREF type ref to CX_LOCAL_EXCEPTION.
    data TEXT type STRING.
    start-of-selection.
        try.
          raise exception type CX_LOCAL_EXCEPTION
                exporting SITUATION = `START-OF-SELECTION`.
        catch CX_LOCAL_EXCEPTION into OREF.
          TEXT = OREF->GET_TEXT( ).
          message TEXT type 'I'.
      endtry.
    In this example, an exception class is derived from one of the predefined exception classes for error situations in the runtime environment. An individual constructor is defined with an individual IMPORTING parameter that supplies the superclass constructor with this parameter. When the exception is handled, the exception text, as defined in the superclass, is read with GET_TEXT.

  • Tangosol Exception class

    Hi,
         I wanted to know if Tangosol provides an exception class of its own. for eg.TangosolException.
         Thanks
         Vinay

    Vinay,
         In general, our API does not declare any checked exceptions.
         Later,
         Rob Misek
         Tangosol, Inc.

  • Can applet load own security class, class loader

    i tried this own security class extends SecurityManager class but exception thrown as applet cannot initate new security manager class.
    i have done throw policy file entry to allow applet to write file in client machine.
    i feel this extra burden novice user...
    what is alternative way....
    plz..

    An applet should never be allowed to install its own security manager. That is why it is burdensome.

  • WF with Exception class issue

    Hi folks.
    I'm on ECC 6.0. I bult a ZCLASS and a Zworkflow which works with a ZCL_class, which works with a ZCX_class (exception class) and its messages.
    Inside workflow, in dialog task/step, I use a PFAC (rule) to determine agent.
    This PFAC rule works fine to get agent. BUT I tryied to force a error (test purpose to see correct ERROR Zmessage in WF log) inside the FM called, but it doens't work. The error is like "Indice ParForEach (id of node).". (I know this error happens when left the correct parameter in bind)....BUT:
    I know this rule works correct when find a agent. BUT when I simulate "no agents", it gives this WRONG error message. I'd like to put my OWN error message.
    Inside the FM called by rule, I instatiated object and I use TRY..CATCH..ENDTRY structure. My CATCH command have a call to exception class and it has the correct message. BUT still not giving (expected) CORRECT ERROR MESSAGE when necessary.
    Thanks.
    Glauco

    Hi.
    Inside the FM, I instantiate a object and call method of Zclass to find user, using TRY..CATCH..ENDTRY.
    TRY.
          CALL METHOD lo_curso->get_usuario_lider
            EXPORTING
              objid_lider   = lv_id_gerente
            IMPORTING
              usuario_lider = l_usuario_lider.
          IF l_usuario_lider IS NOT INITIAL.
            CONCATENATE 'US'
                        l_usuario_lider
                        INTO l_actor.
            APPEND l_actor TO actor_tab.
          ENDIF.
        CATCH zcx_hcm_curso .
          RAISE nobody_found.
      ENDTRY.
    OBS.: I also tryied to use (coment RAISE nobody_found.) nd put OO exception, but when verifying code, give error "Old and new exceptions cannot be used at the same time".

Maybe you are looking for

  • Printer offline when connected to Time Capsule

    I moved my HP All-In-One C4580 from my office to my home. At home, I use my Time Capsule as my primary wireless router. I have followed every step that HP tells me, in terms of removing and reinstalling the software, and still, the only way I can pri

  • Error 1075: The dependency service does not exist or has been marked for deletion

    Windows 7 Pro laptop will not connect to corporate domain. Multiple identical twin laptops have no problem. Best suggestion so far has been to leave the domain and rejoin it, BUT the relevant buttons are grayed out and the comment says "Note: The ide

  • IPod "cannot be updated.  The current file is in use."....how to fix?!

    I have a MacBook and the iPod Nano that came with it. I also have a 4G(I think) 20GB iPod. I have both configured to my Macbook, using only certain playlists to be updated on each iPod. I don't get any problems when I connect the 20GB iPod(w/ the Fir

  • Importing Photos from iPhoto

    When I click on a photo from my iPhoto library the image may or may not display in the viewer window. All my images in iPhoto are jpegs. Recently I purchased a D80 Nikon SLR and have been importing my images into iPhoto. Today I attempted to make a s

  • Clearing of open items using t-code F.13

    Dear Senior Folks ,                          In  the transaction F.13  if the balance is maintained zero for the line items then only it is getting cleared off . If they are non zero balance and also some credit and debit item matches the items are n