Try-catch & throw Exception Question

Method evenNumber can throw IOException, and the caller of method
evenNumber (in this case, method evenNumberTest and method evenNumberTest2)
should catch the IOException. Otherwise, it will have compile
error as the one in method evenNumberTest2.
My question is when I run the program, it will have output "catch evenNumberTest",
but it doesn't output "throw testNumber" Why is that?
I thought ""throw new IOException("throw testNumber");"" will print
"throw testNumber" when it throws the IOException.
So in what situation "throw testNumber" will print it out??
Please advise. Thanks!!
=======================================================
import java.io.*;
public class ExceptionTest
private void evenNumberTest()
{     try
     { evenNumber(2);
     catch(IOException e)
     { System.out.println("catch evenNumberTest");
ExceptionTest.java:14: unreported exception java.io.IOException; must be caught
or declared to be thrown
{   evenNumber(2);
^
     private void evenNumberTest2()
{     evenNumber(2);
private void evenNumber(int x) throws IOException {
     if (x % 2 == 0)
     throw new IOException("throw testNumber");
public static void main(String[] args)
{     ExceptionTest e = new ExceptionTest();
     e.evenNumberTest();

Exception messages aren't printed out when the
Exceptions are thrown.
They are only printed if you explicitly print them, or
if you do not catch them.He is talking about this print statement within the catch block
catch(IOException e)
{ System.out.println("catch evenNumberTest");

Similar Messages

  • Try/catch/throw

    I get confused on the try/throw/catch relationship. The way I read it, try trys to do a bit of code, and if it errors, the catch would be called for the specific error and what to do about it, but does the throw specify a new catch in the try section?
    Would the throw work the same if it was coded as a completely different catch, or is the throw based on a different type of error (logic error versus user error)?
    try
    to do this
    if (something bad happens)
    throw (specific error to go to a new catch)
    catch (What went wrong)
    what to do about it
    catch (new catch)
    what to fix the specific error
    I would appreciate any help....Thanks

    Regarding Paternostro's response:
    So, is it true that the exception is passed up the
    calling stack and will be caught by some other catch
    block?It is true that the exception is passed up the calling stack, but it will only be caught if the caller catches it. In the earlier example, it was not necessary that setLastName( ) declare that it throws an IllegalArgumentException because that is a runtime exception. Only checked exceptions need to be caught or declared as being thrown.
    So, if setLastName( ) threw say, an Exception, then it would have to declare that it throws it in the method declaration, and either it or the caller would have to catch for it or declare that it, in fact, throws Exception. The checks would keep propagating up until it is either handled or unhandled.
    Jeff

  • Try catch throw with doScript()

    Hi,
    Today is my InDesign Scripting Bug Day... grrr. In the following example, the Error e in line 6 is undefined. When I run the Function run() without doScript() it works as expected. It looks like, throw isn't implemented correct with doScript(). At least the throw statement works but does not carry the Error. This is not working in CS4 and CS5.5.
    try {
        app.doScript(run, ScriptLanguage.JAVASCRIPT , undefined, UndoModes.ENTIRE_SCRIPT, "PX_TEMP");
    //~    run()
    catch (e) {
      $.writeln("Caught: " + e.message);
    function run() {
            throw new Error("Im an error");

    The try...catch structure is very specific in that it creates (and destroys) at runtime its own variable scope to target the Error object. I don't know exactly how app.doScript is implemented but there are some reason to believe that the error thrown in the inner script cannot go back to the outer try...catch scope. The error object is probably lost when the inner script returns.
    An ugly solution is to catch the error within app.doScript, to backup the object in a safe place and to re-throw the same error in the outer try block:
    function run(){ throw new Error("Im an error"); }
    run.error = null;
    try {
        app.doScript('try{ run(); } catch(eInner){ run.error=eInner; }');
        if( run.error ){ throw run.error; }
        // you can throw other errors here
    catch(e)
        alert( "Caught: " + e );
    But I hope you have a really good excuse to do such a thing!
    @+
    Marc

  • Catching throwing exceptions

    I want to throw a NoSuchElementException if the next node that gets read does not exists but when I do so I get a NullPointerException. How do I fix this?
    try { 
    Object o= currentNode.getData(); //this is where the nullexception happens
    currentNode=currentNode.getNext();
    return o;
    catch (NoSuchElementException e) {
    throw new NoSuchElementException();
    }

    1. There is little sense catching a NoSuchElementException if you are just going to throw a new one (in the catch block)
    2. Assuming currentNode is null
    if (currentNode==null) throw new NoSuchElementException("currentNode is null");
    return currentNode.getData();

  • OutOfMemory Exceptions on Servlets, Try-Catch unable to help

    Hi, I'm playing with Java servlets right now and I seem to be getting some OutOfMemory errors. The weird thing is that even though I had identify the souce of error and tried to enclose it with a try-catch, the exception still occurs. Why is that so?

    OutOfMemoryError is actually a java.lang.Error, not a RuntimeException. So if you use a try/catch like this
    try {
      // stuff
    } catch (Exception e) {..}Errors will fall through, since Error is not a subtype of Exception. (Check the API.)
    You can catch it by catching Error or Throwable, like this:
    try {
      // stuff
    } catch (Error e) { //  this is rarely a good idea
    }But you normally wouldn't want to do this. When there's no memory left, there's not a whole lot you can do about it, and most of the code you might want to put inside the catch block will merely throw another OutOfMemoryError.
    As voronetskyy said, you're either creating too many (or too large) objects (typically in an endless loop), or you have specified too little memory for your application.

  • Does Labview have Try Catch exception handling?

    1) Does Labview have Try Catch functions, exception handling?
    2) Can Labview access a file or download a file using http or https?
    3) How can labview  read data from an ex ternal server http or https?
    This is in labview 2009 or 2011

    Hi E,
             1. you can chain together your VIs with the error wires, such that if an error occurs in one of them, none of the following VIs will execute.  That's  like throwing an exception - it interrupts the execution chain.  You then "catch" that exception by putting an error handler wherever necessary, but not necessarily in every single VI.Hope  You wouldn't put try..catch inside every single .NET function, instead you handle the exception at the level at which is most appropriate. Same thing can be done in LabVIEW.
    Also see this.
    2. The attached example downloads a picture with http "GET" command.
        Dilbert.Main_LV71.vi 160 KB
    3.see this thread:
       http://forums.ni.com/t5/LabVIEW/Read-a-text-file-from-Labview-web-server-http/td-p/267434
    Yes!!The same thing pointed out by nijims.
    Thanks as kudos only

  • How does it work : String MethdName (argument) throws Exception {}

    HI,
    I am very new to Java. I was looking through some code written by some other developer.
    the code looks like
    String MethdName (argument) throws Exception {
    // some code here
    What it exactly means? Are we forcing this method to always throw an exception? or only if some exception occurs then it will throw the exception?
    Regards,
    Lucky

    It doesnt throw exceptions always.
    What this means is that if you code inside the method does use some API or function that throws exceptions when a particular condition is not met, you method would throw the same exception to it's caller. If you didn't add the throw exception clause in your method, you would have to try/catch the exception that would be thrown in your code.
    Or else, your code won't compile.
    Summary:
    A method that throws an uncaught, checked exception must include a throws clause in its declaration.
    Read this for some additional info:
    [Java Exception Handling|http://ajaxweb.wikidot.com/java-exception-handling]
    [Sun Java Tutorial - Exceptions|http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html]

  • Try catch implementation in dynamic query

    I am fetching values by dynamic selection  (select a,b,..from (var)...) .
    Eveytime if I am selecting garbage value of var it will throw dump . Can u tell me how we implement try catch method / exception handling method so that I can avoid dump in dynamic query
    Appropriate answer will rewarded with points  that is for sure .

    Here is the usage  of th try statements ...
    PARAMETERS number TYPE i.
    DATA: result TYPE p LENGTH 8 DECIMALS 2,
          oref   TYPE REF TO cx_root,
          text   TYPE string.
    TRY.
        IF ABS( number ) > 100.
          RAISE EXCEPTION TYPE cx_demo_abs_too_large.
        ENDIF.
        PERFORM calculation USING    number
                          CHANGING result
                                   text.
      CATCH cx_sy_arithmetic_error INTO oref.
        text = oref->get_text( ).
      CATCH cx_root INTO oref.
        text = oref->get_text( ).
    ENDTRY.
    IF NOT text IS INITIAL.
      WRITE / text.
    ENDIF.
    WRITE: / 'Final result:', result.
    FORM calculation USING    p_number LIKE number
                     CHANGING p_result LIKE result
                              p_text   LIKE text
                              RAISING  cx_sy_arithmetic_error.
      DATA l_oref TYPE REF TO cx_root.
      TRY.
          p_result =  1 / p_number.
          WRITE: / 'Result of division:', p_result.
          p_result = SQRT( p_number ).
          WRITE: / 'Result of square root:', p_result.
        CATCH cx_sy_zerodivide INTO l_oref.
          p_text = l_oref->get_text( ).
        CLEANUP.
          CLEAR p_result.
      ENDTRY.
    ENDFORM.
    <b>please see this  link for detailed  explaination  of the TRY & ENDTRY  ...</b>
    <a href="http://">http://help.sap.com/saphelp_nw04/helpdata/en/a9/b8eef8fe9411d4b2ee0050dadfb92b/content.htm</a>
    reward  points if it is usefull......
    Girish

  • Exception handling with try/catch in acrobat

    Hi
    I have a problem using a try/catch block in my acrobat document-script. Try to enter the following into the debugger-console:
    try{nonexistentFunction();}catch(e){console.println('\nacrobat can't catch')}
    and run it. The output will be:
    nonexistentFunction is not defined
    1:Console:Exec
    acrobat can't catch
    true
    The whole point of a rty/catch block is for the application  NOT to throw an exception, but instead execute the catch-part of the  statement. However, acrobat does both: It throws an exception AND  executes the catch-block.
    Is there another way to suppress the exception, or to make the try/catch-block work as it's supposed to?

    > Also Adobe provides for free the JS or compiled file for Acrobat Reader to support the JS console.
    Where is that file located ? How to install it or where to place it ?
    What is the method referred by try67 on his site where he sells a product ?
    Is that the same as the compiled file you refer to ? or did he sell his solution to adobe ?
    It is helpful if people can get an idea of the nature of choices available and make informed decisions, than a cloak and dagger approach.
    For some jobs that we have, I have been very frustrated by a consultant who wont even give basic info for transparent billing despite all assurances for privacy, as a result we are forced to do the job ourselves.
    Dying Vet

  • Try - catch question..

    hello..
    i was wondering if i can use a try-block and catch a built in exception without explicitly throwing the exception..
    example:
    try{
    foo[5] = 'A';
    catch (IndexOutOfBoundsException e)
    { blah blah
    is this possible w/o throwing the IndexOut... exception in the try statement?

    You can only catch those exceptions that are (or could be) thrown. The reason your code snippet works is that the exception you're catching is a subclass of RuntimeException. You can always catch any RuntimeException and the compiler will OK it, and you don't have to declare them as being thrown either. If you try to catch an Exception that isn't a RuntimeException (like java.lang.Exception) and isn't thrown, you'll get a compile error. That said, I agree that this isn't the way to do it here.

  • Question about throwing exceptions

    hi,
    i am trying to throw a FileNotFoundException in a certain situation, but Eclipse is giving me the 'unhandled FileNotFoundException' error and insisting I wrap the 'throw' statement in a try/catch statement.
    Is that right? is it just a bug in eclipse or does this exception insist i catch the very exception i am trying to throw?
    thanks!

    You can throw it, but you have to declare that your method throws it.
    void myMethod() throws FNFExc {
        throw new FNFExc("Me no findey");
    }

  • Can't throw exception inside try block!

    Hi,
    I'm having a problem trying to throw an error inside a try block.
    To illustrate:
    public class TestException {
    public TestException() {
    try {
    int ret = foo();
    System.out.println("ret is " + ret);
    } catch (Exception ex) {
    System.out.println("exception caught");
    public int foo() throws Exception {
    int ret = 0;
    try {
    throw new Exception("test exception");
    } finally {
    return ret;
    public static void main(String[] args) {
    new TestException();
    If I run this the only output is "ret is 0" - I do not catch the thrown exception! What am I doing wrong?
    Any and all help will be very gratefully received.
    Thanks.

    I need to correct myself: I've re-read the spec, and actually the behaviour is conformant with the JLS: JLS says that the return statement completes abruptly, and an abrupt return in a finally block that didn't have a (applicable or any) catch block will result in the original exception being 'forgotten'.
    Very unintuitive, but as-spec'ed

  • Doubt on try/catch exception object

    why it is not advisable to catch type exception in try catch block. Its confusing me. If i catch exception object then it will show whatever exception occured.
    btw, i was just go through duke stars how it works and saw this
    http://developers.sun.com/forums/top_10.jsp
    Congrats!

    Because there are many different kinds of Exception. If you have some specific local strategy for dealing with a particular excepion then you should be using a specific catch block.
    If you don't then you should allow the expection to end the program, and ideally you should deal with all the expceptions in one top-level handler, so you should throw, rather than catch the exceptions in your methods. Often at the outer most level of the program or thread you will actually catch Throwable (not just Exception) to deal with any unanticipated problems in a general kind of way.
    Also, you should be keeping track of what exceptions might be thrown, so that rather than using Exception in a throws clause or catch block, you should use the particular exceptions. Exceptions, generally, indicate a recoverable error that you really ought to be recovering from rather than just printing a stacktrace.
    That's why exceptions are treated differently from runtime errors.

  • Some simple question , but i dont know...try & catch ..

    Hi i was working on a media player and i've faced some problems...like what exactly does the try&catch do ??
    and in the Player class what the realize() and prefetch do ??
    Thank you in advance..
    Mulham Haffar

    If you are in doubt when or what exceptions to catch, use the java compiler as your guide. You will get compile time errors that clearly name the exception you have to catch with the line of code that could cause the exception/error. Then do the following:
    try {
      // the code that could throw the exception
    } catch ([the-name-exception] e) {
      e.printStackTrace();
      // or do something else relevant here - this code gets executed when the exception is thrown
    } finally {
      // this is an optional block that is always executed before returning from the method (even if there was an exception thrown - do stuff like closing resources here
    }where [the-name-exception] is the exception class I mentioned earlier.
    You can also declare a method to throw the exception if you don't want to catch it. Just use the keyword "throws" followed by the class name of the exception. Then any place where you call the method will have to catch the exception.
    You can also find out what exceptions are being thrown by looking in the JavaDocs. There is plenty more, but that is what you will need to get your program compiling.

  • Catching or Methods Throwing Exceptions

    Hi,
    I'm just wondering whats the difference between catching an exception and a method throwing an exception?
    I'm a bit confused on their purpose dealing with exceptions.
    catching an exception
    void p1()
              try{
                   p2();
              }catch(IOException ex){
         }method throwing an exception
    void p1() throws IOException
              p2();
         }

    one more stuff i need to add is that:
    When we declare a particular code within a try catch
    statement it means that that particular code is very
    much prone to an exception , i mean the programeer
    knows that code will throw a exception and hence we
    mention in try catch block.
    But in other case when we suffixed that particular
    method with throws clause it means the programmer is
    not sure ,that code might throw an exception,hence we
    put in throws clause.Not quite, the programmer always knows if a checked exception is being thrown, since the compiler requires it to be caught or having a throws clause. Unchecked (runtime) exceptions don't require a throws clause and the programmer must/can catch it if he wants to.

Maybe you are looking for