Question on exception catching

Runtime exceptions are not subject to the Catch or Specify Requirement
I came across this line in the Java tutorial at http://java.sun.com/docs/books/tutorial/essential/exceptions/catchOrDeclare.html
What did it mean?

I understand some of what you write but I don't see
how a compiler does not detect it. Sorry if I am
sounding dumb. I never programmed before.Okay, more detailed explanation (which means I am in a good mood otherwise I don't like writing so much):
Consider the following code.
String s = null;
// some code in between
System.out.println(s.substring(0,1));What do you think will happen to this code? It will generate a NullPointerException when substring() is called on the String s unless something else is assigned to the s in between. Now this is something which can occur only when you execute your code.
What I mean is, is there any way for the compiler to detect whether the value of the String variable s has changed? The answer is a plain no. It is not the job of the compiler to know that. So subsequently, a compiler cannot dictate to the programmer that a possible NullPointerException (NPE) needs to be handled because there is no way a compiler could be sure about a NPE in any case (unless it is too smart). There could be several other such exceptions which could occur. So that becomes an unchecked exception which is not checked by the compiler.
Now coming to checked exception. If you are calling a method which already throws an exception as a known behaviour, the compiler is already aware. For example, a file read operation (I'm being lazy in typing code now) would throw an IOException which is defined as a part of the method signature. This makes the compiler aware of the possibility of getting an IOException. SO it checks to see if the programmer has taken care of the exception to make the code more fool-proof. This comes to be known as a checked exception.
Does this make something clear? I hope so.

Similar Messages

  • Question in Exception

    I have a question in the below program. It gives the following results.
    inside try*
    in catch block*
    The value:10</stro
    what happen to that catch block return 5?
    public class T2 {
    public int methodTest(){
    try {
    System.out.println("inside try");
    throw new Exception();
    }catch(Exception ex){
    System.out.println("in catch block");
    return 5;
    finally{
    return 10;
    public static void main(String[] args) {
    T2 t2= new T2();
    System.out.println("The value:"+t2.methodTest());
    }

    raghu182 wrote:
    bq. > \\ JoachimSauer wrote:Having a return or a throw statement in the finally block is usually considered bad practice exactly because of this problem: It can totally hide the effect of any previous return or throw. \\ \\ So in that case, even if you return anything in catch will be ignored by JVM. Am i right?
    If by "in that case", you mean returning or throwing from finally, then yes.
    If you return, throw, break, or continue out of finally, then any completion (return, throw, break, continue) that had been done by try or catch is superceded.

  • How to get details about Exception catched in Exception branch of the Block

    Hello Experts,
    Is it possible to get details about Exception catched in Exception branch of the Block in Integration Process (BPM)?
    In the Exception branch System Error is catched, but from time to time different type of System Errors are happening during sync call to WebService - Connection Timeout, Connection Refused, UnknownHost, etc.
    So the task is somehow to map the type of System Error to the response. I was trying to create a mapping using as source the message which is coming from the Adapter after the sync call, but the mapping is failing with "No Source Payload" error.
    Maybe the description is somewhere in Header or Dynamic configuration?
    Or it is possible to access it somehow with JAVA-maping?
    Thanks for your help!

    Hey,
          the message from the exception can be utilized by using alerts(in order to mail,sms r fax). but otherwise its not possible using mappings or container.
    check this link for alert configuration.
    /people/michal.krawczyk2/blog/2005/09/09/xi-alerts--step-by-step

  • Exception catching, avoiding (sometimes)

    hello,
    i use forte for java and each time i use methods that either read or write to/from a stream without the try catch quotes, i get an error
    Test_Sum.java [58:1] unreported exception java.io.IOException; must be caught or declared to be thrown
    i understand that it is good convention to use the try/catch handlers and do it when writing production code but at times when one just wants to test something, this gets annoying. even some of the tutorial examples do not use these. how do i force the exception catching requirement off?
    thanks in advance jiri

    catch the exceptions you want, and have all methods that might throw an exception declare
    throws Exception
    or
    put everything in a method in 1 try catch block
    mymethod()
      try
      catch (Exception e)

  • Question about Exception Error

    I'm writing a small PBE program for a class project and I keep getting an InvalidKeySpecException that claims my char[ ] is not ASCII. Now I am under the impression that when a char value is entered it's in ASCII values... I've only put up a piece of my code, if needed I can put up the rest, it's fairly simple and easy to follow.
    here is my terminal output (with a number of debug outputs):
    Encryption Program Started
    Getting Password
    Input password (32 character max):
    hello
    Holdspot is: 6
    Pass: hello
    Holder: (shows string of char (0) values, verifies that the array was cleared)
    Done getting password, pass is:
    hello
    Creating PBEKeySpec
    My keySpec value is: hello
    Creating Salt
    createSalt entered
    Done getting salt
    Creating PBEParameterSpec
    setParams entered
    My iteration field is: 1500
    Done getting param
    My param iterations are: 1500
    Creating SecretKey
    createKey Entered
    My keySpec value is: hello
    InvalidKeySpecException: Password is not ASCII
    java.security.spec.InvalidKeySpecException: Password is not ASCII
         at com.sun.crypto.provider.PBEKey.<init>(DashoA6275)
         at com.sun.crypto.provider.PBEKeyFactory.engineGenerateSecret(DashoA6275)
         at javax.crypto.SecretKeyFactory.generateSecret(DashoA6275)
         at Cryptography.createKey(Cryptography.java:141)
         at Cryptography.main(Cryptography.java:265)
         at __SHELL3.run(__SHELL3.java:7)
         at bluej.runtime.ExecServer.vmSuspend(ExecServer.java:178)
         at bluej.runtime.ExecServer.main(ExecServer.java:143)
    java.security.spec.InvalidKeySpecException: Password is not ASCII
         at com.sun.crypto.provider.PBEKey.<init>(DashoA6275)
         at com.sun.crypto.provider.PBEKeyFactory.engineGenerateSecret(DashoA6275)
         at javax.crypto.SecretKeyFactory.generateSecret(DashoA6275)
         at Cryptography.createKey(Cryptography.java:141)
         at Cryptography.main(Cryptography.java:265)
         at __SHELL4.run(__SHELL4.java:7)
         at bluej.runtime.ExecServer.vmSuspend(ExecServer.java:178)
         at bluej.runtime.ExecServer.main(ExecServer.java:143)
    here is my code to get the char array input:
        private char[] getPass () throws IOException{
            System.out.println("Input password (32 character max):");
            char[] holder = new char[maxChar];
            int holdspot=0;
            while ((holder[holdspot++] = (char) System.in.read()) != '\n') {};
            //Debug
            System.out.println("Holdspot is: "+holdspot);
            //End Debug
            char[] pass = new char[holdspot];
            System.arraycopy (holder, 0, pass, 0, holdspot);
            //clear our holder array
            for (int i=0; i<holder.length;i++){
                holder=0;
    //Debug
    System.out.print("Pass: ");
    for (int i=0; i<holdspot;i++){
    System.out.print(pass[i]);
    System.out.print("\n");
    System.out.print("Holder: ");
    for (int i=0; i<holder.length;i++){
    System.out.print(holder[i]);
    System.out.print("\n");
    //End Debug
    //Comment back in for final version, screen clear
    //System.out.flush();
    return (pass);
    here is my code at the point where the exception is thrown:
        private SecretKey createKey(PBEKeySpec keySpec)
        throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException{
            //Debug
            System.out.println("createKey Entered");
            char[] L = keySpec.getPassword();
            System.out.print("My keySpec value is: ");
             for (int i=0; i<L.length;i++){
                System.out.print(L);
    //End Debug
    SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    SecretKey secKey = keyFac.generateSecret(keySpec);
    return (secKey);

    OK, got to Eclipse and reproduced the problem using your code.
    Something about the way you were reading your password bugged me. I changed your code a bit to the following:import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import java.security.spec.InvalidKeySpecException;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.PBEKeySpec;
    public class PBETest {
      static final int MAX_CHAR = 32;
      private char[] getPass() throws IOException {
        System.out.print("Input password ("+MAX_CHAR+" character max):");
        String s = new BufferedReader(new InputStreamReader(System.in)).readLine();
        char[] holder = s.toCharArray();
        int holdspot = (s.length()>MAX_CHAR?MAX_CHAR:s.length());
        //End Debug
        char[] pass = new char[holdspot];
        System.arraycopy(holder, 0, pass, 0, holdspot);
        //clear our holder array
        for (int i = 0; i < holder.length; i++) {
          holder[i] = 0;
        //Debug
        System.out.print("Pass: ");
        for (int i = 0; i < holdspot; i++) {
          System.out.print(pass);
    System.out.print("\n");
    System.out.print("Holder: ");
    for (int i = 0; i < holder.length; i++) {
    System.out.print(holder[i]);
    System.out.print("\n");
    //End Debug
    //Comment back in for final version, screen clear
    //System.out.flush();
    return (pass);
    private SecretKey createKey(PBEKeySpec keySpec)
    throws NoSuchAlgorithmException, InvalidKeyException,
    InvalidKeySpecException {
    //Debug
    System.out.println("createKey Entered");
    char[] L = keySpec.getPassword();
    System.out.print("My keySpec value is: ");
    for (int i = 0; i < L.length; i++) {
    System.out.print(L[i]);
    //End Debug
    SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    SecretKey secKey = keyFac.generateSecret(keySpec);
    return (secKey);
    public static void main(String[] args) {
    try {
    PBETest ptest = new PBETest();
    char[] pwd = ptest.getPass();
    PBEKeySpec spec = new PBEKeySpec(pwd);
    SecretKey sk = ptest.createKey(spec);
    } catch (Exception e) {
    e.printStackTrace();
    }And now it works.
    I don't know exactly why your "one char at a time from System.in" bugged me, and I don't know exactly why it didn't work - but that was the problem.
    Grant

  • IO or FileNotFound Exception catch does not work for getRequestDispatcher

    Hi,
    I am trying to catch IOException / FileNotFoundException in my servlet for the call to getRequestDispatcher().forward(request, response) and than throw user define exception from that catch. I am using JDeveloper 10.1.3. Some how the control is not going to catch block when the file does not exist to forward. But instead JDeveloper is throwing its own exception with error mesg
    NOTIFICATION J2EE JSP0008 Unable to dispatch JSP Page : java.io.FileNotFoundException:
    and browser shows standard 404 File Not Found error page. I would rather have want to display appropriate error page. Here is my code:
    try
    System.out.println("in try");
    context.getRequestDispatcher("/" + currentScreen).forward(request, response);
    System.out.println("after try");
    catch(java.io.IOException fileNotFoundEx)
    System.out.println("runtime exception");
    logger.error(CLASS_OBJECT, "f n f "+RootException.getStackTraceString(fileNotFoundEx));
    throw new RequestHandlerException("requestHandlerError", fileNotFoundEx);
    Here is the output on console:
    06/08/01 10:35:18 in try
    2006-08-01 10:35:18.921 NOTIFICATION J2EE JSP0008 Unable to dispatch JSP Page : java.io.FileNotFoundException: F:\JavaProjects\WorkspaceDev\CorAssessment\web\jsp\assessment_multi_view1.jsp (The system cannot find the file specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:106)
    at java.io.FileInputStream.<init>(FileInputStream.java:66)
    at oracle.jsp.provider.JspFilesystemResource.fromStream(JspFilesystemResource.java:150)
    at oracle.jsp.parse.XMLUtil.getFromStream(XMLUtil.java:228)
    at oracle.jsp.runtimev2.JspPageCompiler.compilePage(JspPageCompiler.java:341)
    at oracle.jsp.runtimev2.JspPageInfo.compileAndLoad(JspPageInfo.java:610)
    at oracle.jsp.runtimev2.JspPageTable.compileAndServe(JspPageTable.java:634)
    at oracle.jsp.runtimev2.JspPageTable.service(JspPageTable.java:370)
    at oracle.jsp.runtimev2.JspServlet.internalService(JspServlet.java:478)
    at oracle.jsp.runtimev2.JspServlet.service(JspServlet.java:401)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
    at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:719)
    at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:376)
    at com.evermind.server.http.ServletRequestDispatcher.unprivileged_forward(ServletRequestDispatcher.java:270)
    at com.evermind.server.http.ServletRequestDispatcher.access$100(ServletRequestDispatcher.java:42)
    at com.evermind.server.http.ServletRequestDispatcher$2.oc4jRun(ServletRequestDispatcher.java:204)
    at oracle.oc4j.security.OC4JSecurity.doPrivileged(OC4JSecurity.java:283)
    at com.evermind.server.http.ServletRequestDispatcher.forward(ServletRequestDispatcher.java:209)
    at com.nexcom.cor.manager.ViewManager.forwardToNextScreen(ViewManager.java:142)
    at com.nexcom.cor.controller.FrontController.doProcess(FrontController.java:85)
    at com.nexcom.cor.controller.FrontController.doGet(FrontController.java:59)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:743)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
    at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:719)
    at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:376)
    at com.evermind.server.http.HttpRequestHandler.doProcessRequest(HttpRequestHandler.java:870)
    at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:451)
    at com.evermind.server.http.HttpRequestHandler.serveOneRequest(HttpRequestHandler.java:218)
    at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:119)
    at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:112)
    at oracle.oc4j.network.ServerSocketReadHandler$SafeRunnable.run(ServerSocketReadHandler.java:260)
    at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:303)
    at java.lang.Thread.run(Thread.java:534)
    06/08/01 10:35:18 after try
    It does not goto catch block and not printing message from System.out.

    You can map error codes to a specific jsp in your web.xml file, and add a parameter to the jsp that will display the message you intend to display back to the user.
    Example:
    <error-page>
    <error-code>404</error-code>
    <location>/index.html</location>
    </error-page>
    You can also trap specific exceptions by doing the following:
    <error-page>
    <exception-type> java.lang.Exception </exception-type>
    <location>/ErrorPage.jsp</location>
    </error-page>

  • JUTreeNodeBinding question (nullpointer exception in getAttribute)

    Hi,
    I've got a question about a piece of code. I've used a JTree which displays a recursive tree, which is working fine. I want to do something when a node is selected. I have the following piece of code:
    jTree1.addTreeSelectionListener(
       new TreeSelectionListener()
         public void valueChanged(TreeSelectionEvent e)
           DefaultMutableTreeNode node = (DefaultMutableTreeNode)jTree1.getLastSelectedPathComponent();
           if (node != null)
             JUTreeNodeBinding tnb = (JUTreeNodeBinding)(node.getUserObject());
             if (tnb!=null)
       });this code is taken from some example I've read on this forum and slightly modified (I can't find the original posting).
    Now, according to the sourcecompletion feature, tnb has methods like getAttribute, getAttributeDef. But when I call one of these methods on tnb (where the '...' is in the example above), I always get a nullpointer exception , somewhere inside the getAttribute call. (the variable 'tnb' itself is not null)
    Why wouldn't this work? Shouldn't the getAttribute calls give me access to the attributes of the row from the view that corresponds the selected element?
    The logwindow shows this for the nullpointer exception:
    Exception occurred during event dispatching:
    java.lang.NullPointerException
         oracle.jbo.AttributeDef[] oracle.jbo.uicli.binding.JUCtrlValueBinding.getAttributeDefs()
              JUCtrlValueBinding.java:173
         oracle.jbo.AttributeDef oracle.jbo.uicli.binding.JUCtrlValueBinding.getAttributeDef(int)
              JUCtrlValueBinding.java:239
         void mypackage.PMyData$1.valueChanged(javax.swing.event.TreeSelectionEvent)
              PMyData.java:332
         void javax.swing.JTree.fireValueChanged(javax.swing.event.TreeSelectionEvent)
              JTree.java:2269
         void javax.swing.JTree$TreeSelectionRedirector.valueChanged(javax.swing.event.TreeSelectionEvent)
              JTree.java:2575
         void javax.swing.tree.DefaultTreeSelectionModel.fireValueChanged(javax.swing.event.TreeSelectionEvent)
              DefaultTreeSelectionModel.java:612
         void javax.swing.tree.DefaultTreeSelectionModel.notifyPathChange(java.util.Vector, javax.swing.tree.TreePath)
              DefaultTreeSelectionModel.java:1006
         void javax.swing.tree.DefaultTreeSelectionModel.setSelectionPaths(javax.swing.tree.TreePath[])
              DefaultTreeSelectionModel.java:288
         void javax.swing.tree.DefaultTreeSelectionModel.setSelectionPath(javax.swing.tree.TreePath)
              DefaultTreeSelectionModel.java:171
         void javax.swing.JTree.setSelectionPath(javax.swing.tree.TreePath)
              JTree.java:1088
         void javax.swing.plaf.basic.BasicTreeUI.selectPathForEvent(javax.swing.tree.TreePath, java.awt.event.MouseEvent)
              BasicTreeUI.java:2117
         void javax.swing.plaf.basic.BasicTreeUI$MouseHandler.mousePressed(java.awt.event.MouseEvent)
              BasicTreeUI.java:2683
         void java.awt.Component.processMouseEvent(java.awt.event.MouseEvent)
              Component.java:3712
         void java.awt.Component.processEvent(java.awt.AWTEvent)
              Component.java:3544
         void java.awt.Container.processEvent(java.awt.AWTEvent)
              Container.java:1164
         void java.awt.Component.dispatchEventImpl(java.awt.AWTEvent)
              Component.java:2593
         void java.awt.Container.dispatchEventImpl(java.awt.AWTEvent)
              Container.java:1213
         void java.awt.Component.dispatchEvent(java.awt.AWTEvent)
              Component.java:2497
         void java.awt.LightweightDispatcher.retargetMouseEvent(java.awt.Component, int, java.awt.event.MouseEvent)
              Container.java:2451
         boolean java.awt.LightweightDispatcher.processMouseEvent(java.awt.event.MouseEvent)
              Container.java:2210
         boolean java.awt.LightweightDispatcher.dispatchEvent(java.awt.AWTEvent)
              Container.java:2125
         void java.awt.Container.dispatchEventImpl(java.awt.AWTEvent)
              Container.java:1200
         void java.awt.Window.dispatchEventImpl(java.awt.AWTEvent)
              Window.java:926
         void java.awt.Component.dispatchEvent(java.awt.AWTEvent)
              Component.java:2497
         void java.awt.EventQueue.dispatchEvent(java.awt.AWTEvent)
              EventQueue.java:339
         boolean java.awt.EventDispatchThread.pumpOneEventForHierarchy(java.awt.Component)
              EventDispatchThread.java:131
         void java.awt.EventDispatchThread.pumpEventsForHierarchy(java.awt.Conditional, java.awt.Component)
              EventDispatchThread.java:98
         void java.awt.EventDispatchThread.pumpEvents(java.awt.Conditional)
              EventDispatchThread.java:93
         void java.awt.EventDispatchThread.run()
              EventDispatchThread.java:85

    Bit of a coincidence.. I was just running into the same problem. But if you check getAttributeDefs(), you'll see that there only is one attribute available, namely the one that is being displayed in the tree. (the 'description'-attribute)
    Or at least, that's the case with my sitation.
    I would love to be able to address all available attributes, eg. foreign key fields, but that doesn't seem possible.
    At the moment, I'm using the following work-around, which of course is far from ideal:
    Key key = tnb.getRowKey();
    ViewObject vo = panelBinding.getApplicationModule().findViewObject("SomeVO");
    Row[] rows = vo.findByKey(key);
    if (rows == null || rows.length != 1)
      System.out.println("Notice: not 1 rows");
      return;
    Row row = rows[0];
    // now you can fetch all the attributes                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Forms question  about exceptions

    Hello,
    I am a newbie and hence my question may find very basic, please help me.
    I have a Pl/sql code where I am executing a queryand if the query doesn't retrieve any values I need to show a message.
    My code is something like this:
    select id from table into tmpid where id=:val_id
    some code here
    CALL_form(url);
    If the query fails I need to show a message, how can I do this. Forgive me for my knowledge in forms, as I am a newbie.
    Thanks in advance.
    Newbie

    Declare
      Found1  varchar2(1);
    Begin
      ...whatever code you need here...
      begin
        select 'Y' into Found1
          from table where id=:val_id;
        exception when no_data_found then null;
      end;
      If Found1 is null then
        Message('No can do!!!');
        Raise form_trigger_failure;
      End if;
      ...some code here...
      Call_form(url);
    End;

  • Question about Exception!

    class A
    public void f() throws Myexcption
    class B extends A
    public void f() throws [Myexception][devied exception from Myexception]
    Why B.f() can only throw less exceptions than A.f()?
    if A temp = new B();
    temp.f() will perform the B.f()'s defination. And if I defined B.f() as
    public void f() throws AnotherException
    throw AnotherException;
    It will has nothing to do with A.f().
    Why did the designer design the less exception throwwing rules?
    Thanks

    class MyFirstException extends Exception {}
    class MySecondException extends MyFirstException {}
    class A {
      public void f() throws MyFirstException { ... }
    class B extends A {
      public void f() throws MySecondException { ... }
    Why B.f() can only throw less exceptions than A.f()?The reason is one of decoupling. If you write code to the contract of A but are actually using an instance of B and the compiler allowed new exceptions to be thrown (not inheriting from the exceptions declared on the original contract) - you would have no way of knowing which other exceptions you must catch. Therefore by enforcing that an overriding method must throw only exceptions within the inheritance hierarchy of the original contract you can be certain to have caught all possible exceptions.
    EG
    A a = new B();
    try {
      a.f();
    } catch(MyFirstException e) { ... }--
    Talden

  • Question on exception variable name

    A very simple question:
    In the following code
    public void compile() {
    ParseTree p;
    try {
    p = parse();
    p.toByteCode();
    catch (ParserException e1) { }
    catch (DumbCodeException e2) { }
    in the first catch clause, the variable name is e1 and e2 for the second catch clause. Can I use the same variable name e for both clauses?
    Edited by: Shibaryotaro on Aug 19, 2009 3:59 PM

    What happens when you try to?

  • Exception Catching

    I was wondering what strategies people use to know what exceptions to try and catch? I would like to be able to know what potential exceptions may be thrown by a method or any method it calls etc.
    For example I was recently working with DefaultMutableTreeNode.insertNodeInto() method, and got the following: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 > 0
    at java.util.Vector.insertElementAt(Vector.java:551)
    at javax.swing.tree.DefaultMutableTreeNode.insert(DefaultMutableTreeNode.java:177)
    at javax.swing.tree.DefaultTreeModel.insertNodeInto(DefaultTreeModel.java:218)
    at CheckTree.CheckTreeModel.addNode(CheckTreeModel.java:88)
    Now I can look up Vector.insertElementAt() and see what exceptions it could potentially raise. However if I look @ insertNodeInto() in the JavaDocs, it doesn't list any potential exceptions that may be raised, nor does it tell me that it uses Vector.insertElementAt().
    Since A. I don't always have all the source code I need to dig through everything I call to see what may cause a problem,
    and B. I don't want to have to go through 3000+ lines of source code just to go, oh look someMethod() can raise a DivideByZero exception! I better be prepared to catch it in my function 6 calls up the ladder.
    So I'm guessing there is a happy medium when it comes to knowing what to look for.
    I know a large part of good code it is making sure your passing sane arguments in your method calls, but when working with new API's it's not always easy to tell what will end up being sane and logical and what will be inappropriate garbage. (Especially with how lacking the JavaDocs can be).
    So like I said I'm wondering what strategies work well for people?

    OKAY Let's take a look at a quote from the first post.
    For example I was recently working with DefaultMutableTreeNode.insertNodeInto() method, and got the following: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 > 0
    at java.util.Vector.insertElementAt(Vector.java:551)
    at javax.swing.tree.DefaultMutableTreeNode.insert(DefaultMutableTreeNode.java:177)
    at javax.swing.tree.DefaultTreeModel.insertNodeInto(DefaultTreeModel.java:218)
    at CheckTree.CheckTreeModel.addNode(CheckTreeModel.java:88) You all should be able to recognize a call stack printed in resoponse to an unhandled exception.
    Let's take a look at the line in bold. Yes I was mistaken about the object calling insertNodeInto().
    But there is a lot of useful information in the callstack, a quick inspection of the callstack reveals
    A. the insertNodeInto called was a method of DefaultTreeModel.
    B. The exception was raised in insertElementAt()
    C. insertElementAt() is called by DefaultMutableTreeNode.insert() which is called by DefaultTreeModel.insertNodeInto().
    Here is a direct copy of DefaultTreeModel,insertNodeInto() java doc:
    insertNodeInto
    public void insertNodeInto(MutableTreeNode newChild,
    MutableTreeNode parent,
    int index)Invoked this to insert newChild at location index in parents children. This will then message nodesWereInserted to create the appropriate event. This is the preferred way to add children as it will create the appropriate event.
    notice a lack of mention of "ArrayIndexOutOfBoundsException" There is a very simple reason for this.
    It is because the exception is raised not by insertNodeInto, but by insertElementAt().
    I am not stating that the documentation for insertNodeInto() is wrong. It is merely not warning me that I may get an exception generated by a method called my a method it itself falls. For which I do not blame it, because insertNodeInto does NOT directly raise the exception.
    I was simply asking what people do to handle exceptions that are generally unforseeable.

  • Exception catching in event processing thread

    Hello!
    How to catch exceptions occurring in event processing thread during repaints, mouse & keyboard event processing etc.? All uncatched exceptions displayed in screen but I need to write them in logfile.
    Anton

    Yes - push your own event processor on to the AWT event queue. See my replies at
    http://forum.java.sun.com/thread.jsp?forum=57&thread=484167
    and
    http://forum.java.sun.com/thread.jsp?forum=57&thread=163020
    Although for two completely different purposes, this technique will also allow you to put your own try/catch around super.dispatchEvent()
    Hope that helps
    Tom

  • Simple questions about exceptions

    why use try catch with new File("filename") but not with x??

    ArrayIndexOutOfBoundsException is unchecked.
    IOException is checked.
    http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html
    Here's a quick overview of exceptions:
    The base class for all exceptions is Throwable. Java provides Exception and Error that extend Throwable. RuntimeException (and many others) extend Exception.
    RuntimeException and its descendants, and Error and its descendants, are called unchecked exceptions. Everything else is a checked exception.
    If your method, or any method it calls, can throw a checked exception, then your method must either catch that exception, or declare that your method throws that exception. This way, when I call your method, I know at compile time what can possibly go wrong and I can decide whether to handle it or just bubble it up to my caller. Catching a given exception also catches all that exception's descendants. Declaring that you throw a given exception means that you might throw that exception or any of its descendants.
    Unchecked exceptions (RuntimeException, Error, and their descendants) are not subject to those restrictions. Any method can throw any unchecked exception at any time without declaring it. This is because unchecked exceptions are either the sign of a coding error (RuntimeException), which is totally preventable and should be fixed rather than handled by the code that encounters it, or a problem in the VM, which in general can not be predicted or handled.

  • Question with " c:catch ".

    <c:catch var="errorMessage">
    <%
    int[] i = new int[2];
    i[2] =2;
    %>
    </c:catch>
    ${errorMessage}
    <%
    // errorMessage.printStackTrace();
    %>
    I use the "${errorMessage}" to print the exception,it works.
    But why i use "errorMessage.printStackTrace();"
    Jsp give out:
    C:\ApacheGroup\Tomcat5.0\work\Catalina\localhost\test\org\apache\jsp\test_jsp.java:250: cannot find symbol
    symbol : variable errorMessage
    location: class org.apache.jsp.test_jsp
    errorMessage.printStackTrace();
    ^

    JSTL variables are not the same as scriptlet variables.
    JSTL variables are stored in the attributes.
    You can retrieve the error into a variable like this:
    Exception e = (Exception) pageContext.getAttribute("errorMessage");
    e.printStackTrace();Also check out this thread:
    http://forum.java.sun.com/thread.jspa?threadID=645936&messageID=3804592#3804592
    Cheers,
    evnafets

  • Question on Exception

    Folks -
          I am facing the following situation with which some of you might be able to help me. I am building a report that has exceptions defined in it for a calculated key figure. This CKF can is calculated as % and can have both positive and negative values.
        The requirement is that the user would enter a % value as variable (lets say he enters 10% when the query refreshes) and based on the value he entered the exceptions should show up on this CKF such that...
    <b>Value of CKF</b>                      <b>Color</b>
               0 %                                      Green
            0.01 to 10 % (variable)              Yellow
            10.01 to 100 %                          Red
    This was easily achieved. But the problem is with the negative values of the CKF! The user wants the color coding even on the negative values such that...
    <b>Value of CKF</b>                      <b>Color</b>
            -100 to -10 %                              Red
            -10 to -0.01 %                           Yellow
            How can I achieve this functionality by using only one variable entry ??? I am looking for an option which does not involve a user exit variable.

    Hi Amol -
          Thanks for your reply. The requirement is such that the user would enter only value for one variable (+ve value like 10%). Using this +ve number, how can I define an exception for the -ve values ?? Like I said above, the exception in this example should be ...
    CKF Value -
    Color
    -100 to -10 -
      Red
    -10 to -0.01  ---  Yellow
          Where 10 is just a arbitrary value and hence have to use variable here. I can achieve this by using two variables...one for +ve values and the other input for -ve value. Please let me know if I am not clear with the requirement.

Maybe you are looking for

  • Unable to form af:table in navigation Menu Model

    Hi, Am using jdeveloper 11.1.2.1.0, I have developed my project with reference to the link below http://www.youtube.com/watch?v=cInX_FMZJaQ Am unable to drag and drop a VO as af:table in my jspx pages. Could any one pls explain me where i went wrong?

  • Encoding

    I have a small problem with encoding! if I use <%include file="file.html"%> it's include that page, but if I have there czech chars, it's show as unreading chars! And it's quite bad! I try to use <meta http-equiv="Content-Type" content="text/html; ch

  • Connecting a gamecube to my Imac?

    Okay, so heres what I have done so far.  I connected my gamecube to an analog/digital converter.  So the red white and yellow wires went into there, and the converter had an HDMI port, so I plugged the HDMI cable into there, and then on the other sid

  • How can get my labels in a screen(dynpro) dynamically .

    Hi All, I have a route screen which has got 6 fields which are the activities in PLPO.So the text of these activites which are 6 are gonna changes.Like let us say for material 5867 I will have to go read PLPO and read VGWTS for it and then on basis o

  • String truncation

    is there an easy way to remove x ammount of characters from a string value?? IE: var greeting = "hello"; (truncate 3 char from the end); trace(greeting) // "he"