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.

Similar Messages

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

  • ABAP OO Exception Class based processing

    Hi there,
    Note: In going forward with SAP WAS 6.20, one can handle exceptions using exception-class based handling using RAISE EXCEPTION TYPE abc and then CATCHing it in TRY/ ENDTRY block. Standard method like GET_TEXT can be used to get the text of the exception raised.
    Question: If I know the EXCEPTION CLASS and Exception ID of my exception class, is it possible to get the exception text directly from the repository without creating the exception class object?
    E.g. Exception class is CX_MY_SECRET_ID
    and Exception IDs for this class are
    ID_NOT_FOUND,
    ID_EXPIRED,
    ID_IS_FOR_SPECIAL_ACCESS
    E.g. last two exception IDs are my warning conditions, and if such conditions are encountered, all I want to do is collect the warning messages. Whereas first exception ID condition (i.e. ID_NOT_FOUND) is an error for me, in which I have pass the exception back to the calling program. E.g. the source code is like this:
    PERFORM.......
    If ID is not found
       RAISE EXCEPTION TYPE ZCX_MY_SECRET_ID
               EXPORTING TEXT_ID = 'ID_NOT_FOUND'.
    else if ID has expired
       ...... then do I have to first raise the exception like raised above and CATCH it before I can get its text? or can I get the exception text directly without raising the exception first (as I know i have to retrieve the text of ZCX_MY_SECRET_ID exception class for Exception ID ID_EXPIRED)?
    In other words, if a certain condition is warning for my program, can I get the condition for that exception (from exception class based on exception class name and exception ID), or do I have to RAISE it first explicitely and then CATCH it immediately and execute GET_TEXT to get its text?
    Thanks very much!

    Hello Chetan,
    in basic the raise exception type xxx creates an exception object and aborts normal execution continuing in the enclosing try block.
    The Abap runtime contains some optimizations regarding the try block has an 'into xxx' clause. But as long you use the same exception you cant take benefit from this.
    As far I understand your problem you have two different kind of severities. So I would use 2 differnt exception classes (maybe derived from a common parent type, or one from the other).
    So both the code which throws the exception and the one which catches it are aware of the different semantic.
    Kind Regards
    Klaus

  • ABAP OO Exception Class

    Class Based Exception Handling involves raising exception (RAISE EXCEPTION TYPE), catching it (CATCH within TRY/ENTRY block) and maybe execute GET_TEXT method to get the text for that exception.
    Allowing exception texts be stored as part of exception classes, does that mean that SAP is moving away from using SAP Message Class (transaction SE91 messages) and relying now onwards upon storing texts in respective Exception Clases?
    My understanding is that SE91 holds not only the texts for exceptions (or hard errors) but also informational and warning messages, and hence if program condition has to display an informational or warning message, there is not need to create an Exception Class for such a condition (and then get the TEXT for that informational message from that Exception Class). Right?
    Pls explain. Thanks much.

    Hi Chetan,
    Sap is not moving away from T100-based (SE91) messages at all.
    In fact you do not store exceptions texts in exception classes but in the OTR (Online Text Repository) and still in T100. If an exception class implements the interface IF_T100_MESSAGE (as of Release 6.40), you can use the statement
    MESSAGE excref TYPE ...
    to display the message after
    CATCH INTO excref.
    It is recommended to use T100-messages for texts send to the user via MESSAGE and OTR-texts for texts not sent to the user but used internally, e.g. for writing into logs.
    Regards
    Horst

  • How to enhance exception class based on CX_ROOT

    I have created an exception class based on CX_ROOT (or CX_STATIC_CHECK, CX_DYNAMIC_CHECK). Now, I need to enhance its "constructor" method with my own parameters. How can I do this? Currently system does not allow this. But, I have seen many other exception classes enhanced the way I want? Any idea?
    Any pointers will be helpful.
    Regards, Neetu

    Hello Neetu
    Two steps are required to get additional IMPORTING parameters in the CONSTRUCTOR method of your exception class:
    (1) Create exception IDs (tabstrip Texts )
    Example:  ID=ZCX_SDN_CLASS, text=Invalid data type for field &FIELD& on screen &SCREEN& &REPORT&
    (2) Add corresponding instance attributes (read-only) to your exception class
    Examples: attributes FIELD, SCREEN, REPORT
    Now the CONSTRUCTOR has the additional IMPORTING parameters FIELD, SCREEN and REPORT.
    If you raise your exception class using id=ZCX_SDN_CLASS then the wildcards (e.g. &FIELD& in the text) will be replaced by IMPORTING parameter FIELD.
    Regards
      Uwe

  • Javax.servlet.jsp.JspException: Exception creating bean of class ProdFormFB

    Hi I am trying to deploy a struts based web application using "DynaActionForms"
    When I am trying to access the jsp page I am getting the following error.
    I am providing as much as details as it can help full to u.
    Thank u.
    FormBean class ProdFormFB.java
    ========================================================================
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import org.apache.struts.action.*;
    public class ProdFormFB extends DynaActionForm
    public void reset(ActionMapping mapping, HttpServletRequest request)
         System.out.println("reset() called. . . . ");
    set("prodId", new Integer(10));
         set("prodName", new String("XYZ"));
         set("price", new Float(22.25));
    public ActionErrors validate(ActionMapping mappings, HttpServletRequest request)
    System.out.println("=== validate() called ===");
    ActionErrors aes=new ActionErrors();
         System.out.println("aes.size() ===> "+aes.size());
         String prodName = (String)get("prodName");
         if( prodName==null || prodName.equals("") )
              System.out.println("Adding prodName.req error . . . . . . .");
              aes.add("prodName",new ActionError ("prodName.req.error"));
    return aes;
    ========================================================================
    Action Class ProdAction.java
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import org.apache.struts.action.*;
    public class ProdAction extends Action
       public ActionForward execute(ActionMapping mapping,ActionForm form, HttpServletRequest request,HttpServletResponse response)throws Exception
          ProdFormFB fb = (ProdFormFB)form;
          System.out.println("fb.get('prodId')==> "+fb.get("prodId"));
          System.out.println("fb.get('prodName')==> "+fb.get("prodName"));
          System.out.println("fb.get('price')==> "+fb.get("price"));
           return mapping.findForward("dres");
    }========================================================================
    jsp page : npform.jsp
    <%@ taglib uri = "/tags/struts-html" prefix="html"%>
    <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
    <html:html>
      <head>
         <title>Product Form</title>
      </head>
      <body>
              <html:form action="/pAction">
              <center>
                <br><br>
                <center> <font color="green" style="bold" size=5>Product Form using Struts</font></center><br><br>
                <table>
                <tr>
                   <td>
                          <b> Product ID : </b>  <html:text property="prodId"/> </td><td><font color="red" style="bold"><html:errors property="prodId"/> </font>
                 </td>
             </tr>
               <tr>
                   <td>
                          <b> Prod Name : </b> <html:text property="prodName"/>  </td><td> <font color="red" style="bold"> <html:errors property="prodName"/> </font>
                 </td>
              </tr>
    <!--           <tr>
                   <td>
                          <b> Price : </b> <html:text property="price"/>  </td><td> <font color="red" style="bold"> <html:errors property="price"/> </font>
                 </td>
              </tr> -->
               <tr  colspan="2" align="center">
                   <td>
                      <html:submit property="submit" value="Store"/>
                </td>
              </tr>
              </table>
                          </center>
           </html:form>
      </body>
    </html:html>========================================================================
    Configuration in struts-config.jsp
        <form-beans>
             <form-bean name="NewProdForm" type="ProdFormFB">
                  <form-property name="prodId" type="java.land.Integer"/>
                    <form-property name="prodName" type="java.land.String"/>
                  <form-property name="price" type="java.land.Float"/>
            </form-bean>
    </form-beans>
    <action-mappings>
           <action name="NewProdForm" path="/pAction" type="ProdAction" input="/npform.jsp" validate="true" scope="request">
                  <forward name="dres" path="/dres.jsp"/>
           </action>
    </action-mappings>========================================================================
    After deploying successfully I am I am entering the following URL
    http://localhost:7001/oursapp/npform.jsp
    The following Exception on Browser: and also on the server console ......
    javax.servlet.jsp.JspException: Exception creating bean of class ProdFormFB: {1}
         at org.apache.struts.taglib.html.FormTag.initFormBean(FormTag.java:463)
         at org.apache.struts.taglib.html.FormTag.doStartTag(FormTag.java:433)
         at jsp_servlet.__npform._jspService(__npform.java:178)
         at weblogic.servlet.jsp.JspBase.service(JspBase.java:33)
         at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run(ServletStubImpl.java:1006)
         at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:419)
         at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:315)
         at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:6718)
         at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
         at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
         at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java:3764)
         at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:2644)
         at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:219)
         at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:178)     
    Plz... Help me out is solving the problem .......
    my email :   [email protected]

    I never used DynaActionForm, what I have noticed here is, don't you need to declare the form bean? I may be wrong.
    <form-beans>
    <form-bean name="newProdForm" type="com.package.form.NewProdForm"></form-bean>
    </form-beans>

  • How to create message based exception class?

    Hi Guys,
    I try to create exception class at Workbech (se24), for example ZCX_TEST. At header information everything is default, but radiobutton "Exception class" is set and checkbox "With message class" is set. After this I enter text for my exceptions, for example TEXT, I assign it to SAP message (for example, class 00, message number 002). I'm going to tabstrip "Attributes" and public constant with name "TEST" should appear with assigned associated type SOTR_CONC and initial value with ID (normal behavior), but attribute "TEST" is created without type and value. It is not possible to use such exception. Where I am wrong?
    Regards,
    Evgeni

    Hmmm. It looks that it works fine with such definitions. Sorry for disturbs.

  • Problem with creating my own class...

    Hi all,
    Purpose with this program:
    I want to create my own class StringThing which take a string parameter and transform the content toUpperCase().
    I have created a simple class StringThing which look like this:
    class StringThing {
    public String upperize (String u) {
    u.toUpperCase();
    return u;
    }And my class where I use the StringThing looks like this:
    import java.io.*;
    class UseStringThing{
    public static void main (String arg[]) throws Exception {
    BufferedReader keyboard = new BufferedReader(
    new InputStreamReader(System.in));
    String s,p;
    System.out.prinln("write a sentence!");
    s=keyboard.readLine();
    StringThing thing = new StringThing();
    p=thing.upperize(s);
    System.out.println(p);
    }Am I not supposed to transform my string parameter in my class by using for instance toUpperCase()? Or is there some fundamental rule or piece of code which I forgot?
    Thanks in advance,
    /Beginner-T-who-ripps-his-hear-over-this-small-problem

    Strings cannot be modified. What this line does:
    u.toUpperCase();
    is to create a new String object. toUpperCase() returns the newly created string and you are ignoring the returned value. What you want to do is:
    return u.toUpperCase();
    or
    u = u.toUpperCase();

  • DAC ERROR EXCEPTION CLASS::: java.lang.NullPointerException

    hello guru,
    when i creating a execution plan in my local envt for testing
    I have assemble the subject area
    but while building the execution plan i am getting below error:
    SHTEST-TEST
    EXCEPTION CLASS::: java.lang.NullPointerException
    com.siebel.analytics.etl.execution.ExecutionParameterHelper.substituteNodeTables(ExecutionParameterHelper.java:174)
    com.siebel.analytics.etl.execution.ExecutionParameterHelper.parameterizeTask(ExecutionParameterHelper.java:141)
    com.siebel.analytics.etl.execution.ExecutionPlanDesigner.getExecutionPlanTasks(ExecutionPlanDesigner.java:738)
    com.siebel.analytics.etl.execution.ExecutionPlanDesigner.design(ExecutionPlanDesigner.java:1267)
    com.siebel.analytics.etl.client.util.tables.DefnBuildHelper.calculate(DefnBuildHelper.java:169)
    com.siebel.analytics.etl.client.util.tables.DefnBuildHelper.calculate(DefnBuildHelper.java:119)
    com.siebel.analytics.etl.client.view.table.EtlDefnTable.doOperation(EtlDefnTable.java:169)
    com.siebel.etl.gui.view.dialogs.WaitDialog.doOperation(WaitDialog.java:53)
    com.siebel.etl.gui.view.dialogs.WaitDialog$WorkerThread.run(WaitDialog.java:85)
    can anyone help on this.
    thanks

    Hello Shiva,
    I have tried to generate the paramenter index in going into execute tab.
    Acutally I have two database one is SH(for sales fact table) as source and other is SHTST (for target w_sales_F).
    when i go into that it try to click on generate button it shows only for SHTST not for SH
    more over in SHTST the value is coming as Informatica folder Sales where i created all mapping.
    SH and SHTST both are in same database oracle 10g.
    please help

  • Exception class help

    Hi,
    i create exception class like it write in the sap help and when i want to send the exception with parameters to the ABOVE METHODS i don't susses  i just get the message without the parameter ?
    there is simple guideline how o transfer the exception with parameters?
    br
    Ricardo

    HI Uwe,
    Thanks,
    This is my sample code:
    This is the first method on the tree:
    the method name is create .
    INSERT (lt_table_name) FROM <ls_obj>.
        IF sy-subrc <> 0.
          RAISE EXCEPTION TYPE /cx_db_db_error
            EXPORTING
              textid     = cx_db_error=>create_failed
              table_name = lt_table_name.
        ENDIF.
    this method call to the above method - create .
    TRY.
            CALL METHOD lo_obj_create->create
              CHANGING
                is_bound_object = ls_obj_user.
          CATCH cx_db_error INTO lo_exc.
            "Create user failed. Throw an exception.
            RAISE EXCEPTION TYPE cx_db_error
              EXPORTING
                textid     = cx_db_error=>create_user_error
                previous   = lo_exc.
            result = lo_exc->get_text( ).
        ENDTRY.
    here in result i just get the massage without the table name that i export in the first method ,what i miss here ?
    Best Regards
    Ricardo

  • How to create an exception....

    i'd like to create an exception for negative numbers....im using commandline arguments and i dont want to accept negative values...
    any suggestions...????

    This should give you some more idea what to do it will show you pertty much about how exceptions work or it will confuse the hell out of you even more lol
    import java.io.*;
    public class junk {
      //Are main program
    public junk() {
        super();
        String[] neg  = new String[10];
        System.out.println("Enter up to 9 numbers if one of them is a neg this program will throw our exception");
        try{
        for(int i =0; i<9; i++) {
         BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
         neg[i] = buf.readLine(); }
        }catch(IOException ee) {ee.printStackTrace();}
         catch(NumberFormatException nfe){nfe.printStackTrace();}
         try {
    /*See here, are junkit.class is just like a reg io .class that throws a ioexception but it will throw are exception cause junkit.class throws are NegativeNumberException that we made so we have to wrap it in the try catch blocks or throw the exception in are main class junk  */
            junkit ju = null;
            for(int j =0; j<neg.length-2; j++) {
            ju = new junkit(neg[j]);}   
            ju.printit();
        } catch(NegativeNumberException nne){nne.printStackTrace();} 
       public static void main(String[] args) {
        junk test = new junk();
    class NegativeNumberException extends Exception {
       //Are new exception class
       public NegativeNumberException() { super();}
       public NegativeNumberException(String msg) { super(msg); }
    class junkit {
    //Are class that will throw are NegativeNumberException
          private String gettheString;
          private int negneg;
      public junkit(String getIt) throws NegativeNumberException {
         gettheString = getIt;
          negneg = Integer.parseInt(getIt);
         if(negneg < 0) {
           throw new NegativeNumberException("Negative numbers not allowed");
      public void printit( ) {
         if(negneg > 0) {
        System.out.print("Great no exception was thrown");}
    }Anyways Good Luck

  • How to use user defined exception class

    Hi all
    I just need som help with creating a user defined exception class.
    Im writing a small/simple text editor.
    My exception class looks like this:
    public class myExcp extends Throwable
         private String message;
         public myExcep(String message)
              this.message = message;
         public void display()
              System.out.println(message);
    I would like to use it when a user tries to open a exe-file instead of a txt file.
    Here is some code from the editor:
    if (e.getSource() == open)
    saveOld();
    if (fc.showOpenDialog(null)== JFileChooser.APPROVE_OPTION)
    readFile(fc.getSelectedFile().getAbsolutePath());           
    saveas.setEnabled(true);                
    So, should I use exception here or at the readFile method?
    readfile:
    private void readFile(String fileName)
    try
    String tmp = fileName.substring(fileName.length() -4, fileName.length());
    if (!tmp.equals(".exe"))
    FileReader r = new FileReader(fileName);
    textarea.read(r, null);
    r.close();
    currentFile = fileName;
    label.setText(currentFile);
    changed = false;
    catch (IOException e)
    JOptionPane.showMessageDialog (this, "Cannot find the file " + fileName);
    Where and how do I use my exception class.
    Do I need to create an instance? Where?
    Should the exception class extend Exception instead?
    Thank you in advance /

    Extend Exception, not Throwable. It's a checked exception that way.
    Follow the Sun coding standards and make that exception class name start with a capital letter.
    When you extend Exception, override all four ctors.
    What's that display method you added? Isn't getMessage() good enough?
    You need to create a new instance just before you throw the exception, of course.
    Sounds like a terrible design, by the way. Exceptions shouldn't be used like "go to" for app logic. They should signal unrecoverable conditions. You can easily recover from the situation you've described simply by displaying a pop-up that tells the user to open only text-readable file types. I think that's a better solution.
    %

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

  • Global Exception Class

    Hi,
    I have a global exception class which is inherited from already existing exception class.
    I would like to use this class to raise different exceptions.
    How to use this global exception class to raise exceptions with different descriptions?
    can anybody explain or send a material on this?
    Thanks in advance...
    Sreenivas Reddy

    I guess you have little misunderstanding of the Exception concept.
    You have to RAISE the exception from any processing block (Subroutine, Method etc.) and CATCH the exception in where you call the subroutine.
    Check this example. In this example, I am raising the exception from the method DEVIDE of the class LCL_TEST. Now, I call this method DEVIDE in the START-OF-SELECTION block. So, here I need to catch this raised exception by the DEVIDE method. In my example I have used the exception class ZCX_GEN_EXC, you may have to replace it with your exception class ZCX_SAMPLE_EXCEPTION.
    CLASS lcl_test DEFINITION.
      PUBLIC SECTION.
        METHODS devide
          IMPORTING
            n1 TYPE i
          CHANGING
            n2 TYPE i
          RAISING
            zcx_gen_exc.
    ENDCLASS.                    "lcl_test DEFINITION
    START-OF-SELECTION.
      DATA: lo_test TYPE REF TO lcl_test,
            lo_exc  TYPE REF TO zcx_gen_exc,
            lf_n1   TYPE i,
            lf_n2   TYPE i.
      CREATE OBJECT lo_test.
      lf_n1 = 0.
      lf_n2 = 10.
      TRY.
          CALL METHOD lo_test->devide
            EXPORTING
              n1 = lf_n1
            CHANGING
              n2 = lf_n2.
    * catching the exception
        CATCH zcx_gen_exc INTO lo_exc.
          MESSAGE lo_exc->wf_etext TYPE 'I'.
      ENDTRY.
    CLASS lcl_test IMPLEMENTATION.
      METHOD devide.
        IF n1 = 0.
          RAISE EXCEPTION TYPE zcx_gen_exc
            EXPORTING
              wf_etext = 'Exception occured'
              wf_mtype = 'E'.
        ELSE.
          n2 = n2 / n1.
        ENDIF.
      ENDMETHOD.                    "devide
    ENDCLASS.                    "lcl_Test IMPLEMENTATION
    Regards,
    Naimesh Patel

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

Maybe you are looking for