CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 18
  1. #1
    Join Date
    Jul 2007
    Posts
    273

    newbie: exception handling (and Eclipse)

    Hello,
    I wrote a class with few methods; inside them I work with IO and XMLReader; now, since I haven't managed the exceptions at all, Eclipse was compaining about that and suggested two thing: surround with try/catch blocks or to add throws declaration close to each method, like this:
    Code:
    String Element() throws IOException, XMLStreamException {
    
    }
    After add those two declaration, suddenly Eclipse wasn't complaining no more.
    My question is:
    1. I read that those declaration don't solve the exception handling BUT only remember to to coder that will use them that he has to manage the exceptions. Right this?

    2. so I suppose I have to addtry/catch inside each method: they are five: do I need repeat 5 try/catch in each methods either I can put just one out of them? and Where?

    thanks

  2. #2
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: newbie: exception handling (and Eclipse)

    You need to read a tutorial on Exception handling such as the Sun tutorial
    1. I read that those declaration don't solve the exception handling BUT only remember to to coder that will use them that he has to manage the exceptions. Right this?
    Sort of. Declaring a method throws an exception is a way of passing the responsibility of handling the exception to the calling method - of course the calling method could also just throw it to it's calling method and so on. If a thrown exception propagates all the way up the call stack and no one has handled it, a stack trace is dumped to the console.

    Remember that there is a class of exceptions called unchecked exceptions such as NullPointerException that a method does not need to declare it throws, but it may still throw them.

    so I suppose I have to addtry/catch inside each method: they are five: do I need repeat 5 try/catch in each methods either I can put just one out of them? and Where?
    You only add try catch statements to methods that can usefully handle the particular exception. If the code can't do something sensible in response to the exception then it should throw it, if it does handle it then the calling method can't handle it as well unless the exception handler re-throws the exception.

    It may also be the case that a method catches some but not all of the exceptions thrown to it - this is perfectly ok. In this type of situation your method declares it throws the remaining exceptions and it up to the calling method to handle them.

    Sometimes the handling mechanism is the same for a number of different exceptions in which case, if they have a common super class, you can just catch the super class. But be careful doing this as you may inadvertently catch exceptions you didn't intend to.

    Also the order of your catch statements is important, if your first catch statement is for a common super class followed by catch statements for sub classes then the sub class catch statements will never be called.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

  3. #3
    Join Date
    Jul 2007
    Posts
    273

    Re: newbie: exception handling (and Eclipse)

    not sure to have understood; BTW, these 5 methods do basically the same operation: reader.next(); however, before to call the next() method, I cal the reader.hasNext() that sohould guarantee that reader.next() will never throws any exception; right, this?
    Yes, in my opinion (as the methods do basically the same operation) the best way would be put try and catch outside them. I was thinking directly in th main() class. Is this awful?

  4. #4
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: newbie: exception handling (and Eclipse)

    What kind of Reader has next() and hasNext() methods? I know ResultSet, Scanner, and Iterator have next() methods, but no Readers.

    It doesn't matter whether you've called hasNext() before next(), if the next() method is declared to throw exceptions, then you need to decide how to handle them. If it isn't, you don't need to.

    [Note that in the case of Scanner, for example, the next() method isn't declared to throw exceptions - so you don't have to write code to deal with them. However, the API docs say that it can throw certain exceptions in some circumstances. These are RuntimeException subtypes, known as 'unchecked' exceptions because you're not obliged to handle them, but if you don't, and the exceptions are thrown, the application will terminate. Generally, you'd only put in code to catch and handle these exceptions if there's a possibility that your code might trigger them - e.g. multi-threaded code where perhaps the Scanner is being accessed by more than one process.]

    You should put your catch code blocks at the closest point where you can handle the exception and do something useful, such as retrying the operation, or tidying up and abandoning the operation. Sometimes this will be in the same method that throws the exception, sometimes in the method that calls that method, and sometimes it will be the main method. Usually, by the time it reaches the main method, there's nothing to do but output an informative error message and quit.

    As soon as we started programming, we found out to our surprise that it wasn't as easy to get programs right as we had thought. Debugging had to be discovered. I can remember the exact instant when I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs...
    M. Wilkes
    Please use [CODE]...your code here...[/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  5. #5
    Join Date
    Jul 2007
    Posts
    273

    Re: newbie: exception handling (and Eclipse)

    Quote Originally Posted by dlorde View Post
    What kind of Reader has next() and hasNext() methods? I know ResultSet, Scanner, and Iterator have next() methods, but no Readers.
    XMLStreamReader

  6. #6
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: newbie: exception handling (and Eclipse)

    As I said earlier the exception handler should be placed where it can do something useful, if that place is the main method then that's the place to put it.

    The XMLStreamReader.next() method throws 2 exceptions the first is NoSuchElementException - but this only happens if the method is called when hasNext() returns false which you are already checking for, so you will never get this exception. The second is XMLStreamException which happens if there is an error processing the underlying XML source. There's probably not a lot you can do about this other than reporting the problem to the user so catch the exception in the code that responded to the user's request to read the XML stream.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

  7. #7
    Join Date
    Jul 2007
    Posts
    273

    Re: newbie: exception handling (and Eclipse)

    Quote Originally Posted by keang View Post
    As I said earlier the exception handler should be placed where it can do something useful, if that place is the main method then that's the place to put it.

    The XMLStreamReader.next() method throws 2 exceptions the first is NoSuchElementException - but this only happens if the method is called when hasNext() returns false which you are already checking for, so you will never get this exception. The second is XMLStreamException which happens if there is an error processing the underlying XML source. There's probably not a lot you can do about this other than reporting the problem to the user so catch the exception in the code that responded to the user's request to read the XML stream.
    OK. I just want to inform the user that something went wrong with the sintax of the file in input.
    But my question was even this: is there a way to evoid duplication of code ? Since I have 5 methods with the same try/catch block, can I put this up (maybe in the Main class), and write just one try/catch clause?

  8. #8
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: newbie: exception handling (and Eclipse)

    If you'd read the link I gave you you would have seen you can put multiple statements in a single try block. So you just need to put all five methods calls within the one try block.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

  9. #9
    Join Date
    Jul 2007
    Posts
    273

    Re: newbie: exception handling (and Eclipse)

    Quote Originally Posted by keang View Post
    If you'd read the link I gave you you would have seen you can put multiple statements in a single try block. So you just need to put all five methods calls within the one try block.
    Maybe my situation is a little different:
    Code:
    //Main
    MyObject ob = new MyObject();
    
    class MyObject {
        public MyObject() {
                  method1();
        }
     public  void Method1() throws IOException, XMLStreamException{
               int event = xmlreader.next();
               if (event == ...........................) {
                   method2();
                ..................
    
                }
      }
    public void Method2() throws IOException, XMLStreamException{
               int event = xmlreader.next();
               if (event == ..................... ) {
                   method3();
                ..................
    
                }
    
      }
    }
    }
    SO I repeat my question: must I put try/catch inside each MethodX either I can put one in main class?
    Last edited by mickey0; July 6th, 2010 at 10:21 AM.

  10. #10
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: newbie: exception handling (and Eclipse)

    SO I repeat my question:
    And I'll repeat my answer - read the tutorial and the information you have already been given.

    Admittedly your code isn't how you had originally described it ie you didn't mention you were chaining the 5 method calls, but the information I gave in my first post explains what will happen if any of the methods throws an exception and the caller doesn't handle it. And dlorde and I both explained where you can put the exception handler.

    There's more than enough information there for you to be able to work it out for yourself - and if you can't work it out write some code and see what happens.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

  11. #11
    Join Date
    Jul 2007
    Posts
    273

    Re: newbie: exception handling (and Eclipse)

    I know you gave me link but I always do confusion with this. I suppose I could do:

    Code:
    //Main
    MyObject ob = new MyObject();
    
    class MyObject {
        public MyObject() throws IOException, XMLStreamException {
                try {
                  method1();
              }
               catch (XMLStreamException ex) {
               }
              catch ( IOException ex) {
               }
        }
     public  void Method1() throws IOException, XMLStreamException{
               int event = xmlreader.next();
               if (event == ...........................) {
                   method2();
                ..................
    
                }
      }
    public void Method2() throws IOException, XMLStreamException{
               int event = xmlreader.next();
               if (event == ..................... ) {
                   method3();
                ..................
    
                }
    
      }
    }
    }
    So method1 and method2 will propagate up the exception (if an exception occur) and the exception will be caught inside method1; with this reasoning I could put the try/catch inside the main class, I suppose.
    is this right?

  12. #12
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: newbie: exception handling (and Eclipse)

    So method1 and method2 will propagate up the exception (if an exception occur) and the exception will be caught inside method1; with this reasoning I could put the try/catch inside the main class, I suppose.
    is this right?
    As dlorde and I have both said you put the handler at the point at which you can do something useful and as close as possible to the place the exception is thrown. If your handler can do what you want it to do where you have it then leave it there - don't move further from the problem than you have to.

    Having said that you haven't done anything useful in the code you have shown. You've just committed the cardinal sin of catching the exceptions and doing nothing at all, not even dumping the stack trace. This just hides the fact that the exception has even been thrown. Always do something in the catch block even if it is just calling the exception's printStackTrace() method.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

  13. #13
    Join Date
    Jul 2007
    Posts
    273

    Re: newbie: exception handling (and Eclipse)

    Quote Originally Posted by keang View Post
    As dlorde and I have both said you put the handler at the point at which you can do something useful and as close as possible to the place the exception is thrown. If your handler can do what you want it to do where you have it then leave it there - don't move further from the problem than you have to.

    Having said that you haven't done anything useful in the code you have shown. You've just committed the cardinal sin of catching the exceptions and doing nothing at all, not even dumping the stack trace. This just hides the fact that the exception has even been thrown. Always do something in the catch block even if it is just calling the exception's printStackTrace() method.

    you're right. My question was only if the try/catch will be "called" fine. In the try/catch I would put simply a message with System.exit(-1) because there's nothing to recover (the XML file is not well written).
    I only wonder if in my case here above exceptions are unuseful! Is the meaning of exception just recovering something?
    Yesterday I wa thinking this: If I don't put try/cach at all the program the program will arise exception (and this is bad); I thought that putting try/catch was even to avoid the program arises exceptions at all! I thought this, but now I suppose this was wrong! try/catch just helps to RECOVER (but the exception will arise anyway). Is that, please?

  14. #14
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: newbie: exception handling (and Eclipse)

    An exception is thrown when some exceptional situation has occurred. If you don't handle a thrown exception it will propagate all the way to your main method and the application will close unceremoniously and dump a stack trace to the console (This is only true for CLI applications like yours, it can be a little different in multi-threaded and GUI apps). The user will be left thinking your application has crashed ie is poorly written, rather than being told it's their data that is at fault.

    but now I suppose this was wrong! try/catch just helps to RECOVER (but the exception will arise anyway). Is that, please?
    It depends what you mean by recover, if you mean handle an unusual circumstance then yes, if you mean to allow the program to continue running then no not necessarily.
    There are plenty of cases where you can't do anything to continue execution but you can still use exception handling to do something sensible before the application terminates ie close down a database connection, write an entry to an error log file, inform the user what has happened etc.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

  15. #15
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: newbie: exception handling (and Eclipse)

    Quote Originally Posted by mickey0 View Post
    XMLStreamReader
    Ah, yes - thanks. That's a 'new' one in Java 6. Sadly, for technical reasons, I'm still restricted to Java 5 day-to-day...

    There are only two kinds of programming languages: those people always bitch about and those nobody uses...
    B. Stroustrup
    Please use [CODE]...your code here...[/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured