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

Similar Messages

  • While local variable initialized inside try block compiler throws error???

    Check out this code where two local variables(one String and the other int type) is declared at the beginning of the method and initialized inside try block. now when i compile this app, it gives an error sayin' that Variables not been initialized. Can anyone tell me why compiler is throwin' an error message?
    Many thanks.
    import java.io.*;
    public class Test{
    public static void main(String[] args){
    String aa;
    int c;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("EnterAnything:");
    try{
    aa = in.readLine();
    c = 1;
    catch(IOException e){
    System.out.println(e.getMessage());
    System.out.println(aa);
    System.out.println(c);
    }

    jfbriere,
    Thanks to u all.
    that every reference to the variable is necessarily preceded
    by execution of an assignment
    to the variable.But I've initialized the variable c and aa inside try block before referencing it as a parameter of println()?
    Can u clarify this?
    --DM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Posiibility for terminating jvm inside try block so that finally block wont

    posiibility for terminating jvm inside try block so that finally block wont execute at all ?
    But in that case what will happen?
    Is it safe for any practical situation ?
    Threads: t.stop()
    JVM : System.exit()
    which one can really help and where?

    What if security Manager comes into picture?
    class ExitCatchingSecurityManager extends SecurityManager
    public void checkExit(int status)
    Process.terminateProcessWithThreadGroup(getThreadGroup());
    throw new SecurityException();
    What if an application calls System.exit()?
    We still have one big hole in our multiprocess library. If any application calls System.exit(), the JVM terminates, and all the pseudo-processes will be destroyed with no warning. Fortunately, Java's design once again comes to our aid. Any call to System.exit() is first checked by the SecurityManager to see if the application has permission to terminate the JVM. We can install our own SecurityManager to catch the System.exit() call, disallow it, and terminate the pseudo-process instead. The SecurityManager is actually quite simple to define:
    class ExitCatchingSecurityManager extends SecurityManager
    public void checkExit(int status)
    Process.terminateProcessWithThreadGroup(getThreadGroup());
    throw new SecurityException();
    In addition, the SecurityManager should define all other checks so that they do not block pseudo-processes from running. A simple null call for all check* methods will work. We install our own SecurityManager by calling System.setSecurityManager(), i.e., by adding the following line near the startup of the multiprocess library:
    System.setSecurityManager(new ExitCatchingSecurityManager());
    The Process.terminateProcessWithThreadGroup() method is simple to define, by holding a collection of Process objects in the Process class, searching the collection to find the Process with the identical ThreadGroup, then terminating that Process.

  • Return statement inside try block

    what is wrong if i write code like as below...please explain me since i am new to java
    class sample{
    public String method(){
    try{
    String str="abc";
    return abc;
    catch(Exception e){}
    }

    veldhanas wrote:
    return abc;In your code there is no varible declared as abc. It is a value assigned in str.
    Suppose if the code in try statement throws exception the return statement is skipped and the
    associated catch block will get executed. So your catch block must return a result of type String.... or throw another (or the same) exception.
    In this case, since there's no way the code in the given "try" block can throw an exception, it would have been better to not even have a try/catch block in the first place.
    And almost never just swallow exceptions like that (an empty catch block). There are only a few cases where it's ok to swallow them (such as in finally blocks where you're cleaning up resources which may throw exceptions while cleaning up, and you want to continue cleaning up and ignore those kinds of exceptions).

  • How can I throw exceptions using JAX-WS 2.0?

    I have been using NetBeans5.5 to develop a web service from a WSDL i.e. I write the XSD and WSDL first then generate the web service code in NetBeans5.5. How can I throw an exception so that details of the exception will be contained within the SOAP xml response? For example:
    <soapenv:Body>
            <soapenv:Fault xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
                   <faultcode>MyFaultCode</faultcode>
                   <faultstring>MyFaultString</faultstring>
            </soapenv:Fault>
    </soapenv:Body>In the above sample message FaultCode and FaultString would be something that I can specify, perhaps the contents of another caught exception. I really need to have some way to display meaningful data to anyone which consumes this web service and where an exception occurs.

    You can throw a javax.xml.ws.soap.SOAPFaultException. https://jax-ws.dev.java.net/nonav/jax-ws-20-fcs/api/javax/xml/ws/soap/SOAPFaultException.html

  • Exception inside a block [BPM]

    I have send step and exception branch inside block. 
    But my exception handler is always triggered independently of sucess/error of my send step.
    Could anybody explain How do exception branch work?
    Where do I find good BPM documentation? I can't find the full documentation with answer on my question.
    Blogs are good but they are not enough
    help.sap.com is't enough too.

    Hi,
    don't read everything:)
    just take a look at the <b>Example</b> section:
    http://help.sap.com/saphelp_nw04/helpdata/en/33/4a773f12f14a18e10000000a114084/content.htm
    with this example I'm sure you'll understand
    Regards,
    michal

  • Can I throw exception in constructor?

    I just want to add some constraints on the object.
    I'm thinking to add the constraints to the constructor, when every time create a new object , check first. If obey the rule, that's fine. If not, just throw it? Can I do like this way??
    e.g Class Distance
    Distance(x){if x >= 0.0  dist = x  else throw...}
    float dist;
    }

    The best exception to throw in that case is IllegalArgumentException..
    class Distance {
        float dist;
        Distance(float x) {
            if (x < 0.0) {
                throw new IllegalArgumentException("x must be non-negative");
            dist = x;
    }

  • Try block inside a try block - who is throwing StaleConnectionException?

    int retry = 0;
    try{ //MAIN TRY
    //GET Datasource from context<---is this throwing?
    boolean retry = false;
    do {
         try {
              retry = false;
    GET CONNECTION FROM DATASOURCE<--or shld this be?
         }catch(SQLException e) {
         //FIRST CATCH
         if (retryattempts++ < 3){
              retry = true;
    } while (retry);
    //DO something which requires try block
    }catch(SQLException e)
    {//Second catch
    When I do this the StaleConnectionException is caught by the second catch... does this mean that the staleconnectionexception is thrown when getting datasource from initialcontext and not while getting connections?
    Edited by: wannaBeACsGrad on Jan 10, 2008 9:09 AM

    I am not sure what your are trying to do. Your code as posted is incomplete and could not possibly compile. The Try/catches do not seem to be nested.
    More importantly, why in the world would you ever want to have a try inside a try? You can have a single try, then several different calls in loops or whatever that can potentially throw Exceptions and then have mulitple catch statements to handle them. For instance, you could have something like this:
    try {
    } catch (NullPointerException ne) {
       // handle null issues here
    } catch (NumberFormatException nfe) {
       // handle number format issues here
    } catch (Exception e) {
       // everything else falls here
    }Keep in mind that you don't want to do any "Error Hiding". Make sure you handle each case appropriately.

  • I can't throw my exception

    I created my exception
    public class wyjatek extends Exception {
        public wyjatekNieobslugiwany() {
    }i can throw him in my code:
       try{
                                    try{
                             x= request.getParameter("x");
                             y= request.getParameter("y");
                        } catch (NullPointerException npe){
                             throw new wyjatek();
                                    if (x.equals(y)){
                                        out.println('equal')
        } catch (wyjatek w){
        }but i have NullPointerException. Code after throw new wyjatek() is executing.
    Why?
    I change line "throw new wyjatek()" to "throw new Exception()" and everything was fine. Why I can properly throw Exception() but I can't throw wyjatek() witch extends Exception()?

    but i have NullPointerException. Code after throw new wyjatek() is >executing.Wrong, that's the code throwing NPE.
    try{
         //A NPE Exception will never be thrown here
           x= request.getParameter("x");
          y= request.getParameter("y");
    } catch (NullPointerException npe){
          throw new wyjatek();
    if (x.equals(y)){ //this is where NPE will be thrown if x or y is null
         out.println('equal')
    }For your exception to be thrown (cant figure out why you should throw CustomExceptions on NP, though)
          x= request.getParameter("x");
          y= request.getParameter("y");
          try{
                     if (x.equals(y)){
                         out.println('equal')
              }catch(NullPointerException npe){
                   throw new wyjatek(npe.getMessage());
          }cheers,
    ram.

  • Catching causal exceptions from finally{} block?

    I have some code that I have not developed, yet from what I can tell throws Exceptions as in the following psuedo-code:
    public void foobar() throws BarException, FooException {
            try {
                  throw new FooException();
            } finally {
                    throw new BarException();
    }This expectedly returns BarException, not FooException. Question is since FooException was thrown, is there any way to get a reference to the original cause?

    This is due to the good-ol' problem of cleaning up
    java.sql.Connection objects to a connection pool in
    the finally block yet wanting to ensure the original
    exception is propagated to the calling method,
    whereas the OP should catch the exception,
    maintain temporary reference, then use it as a
    reference to the other Exception in the finally
    if there's no better way for her to do it.There's a better way to do it. You don't need to keep a temp reference to that exception in your finally block. Finally doesn't need to know anything about the exception. public void foo() {
        try {
            Bar bar = sqlStuff();
        catch (SQLException exc) {
            // This catch block will execute if  SQLException is thrown at *1*
            System.err.println("I got a SQLException!");
    private Bar sqlStuff() throws SQLException, MyException {
        try {
            // *1* do something that might throws SQLException, and maybe something else
            return aBar;
        catch (SomeOtherException exc) {
            throw new MyException(exc);
        finally {
            // close ResultSet, Statement, Connection
            // NO EXCEPTION re-throwing
        // or return aBar here
    } If a SQLException is thrown inside the try block, finally will execute, and then the method will throw that original SQL exception. If SomeOtherException is thrown, it will be caught, a new MyException will be created to wrap it, the finally block will execute, and the MyException will be thrown from the method. If everything goes well, the finally block will execute, and the method will return aBar.
    All this will happen without the finally block touching or knowing about any exception that was thrown before entering it.

  • Throws Exception - a newcomer...

    I have written a small amount of code that takes information from a text file and displays it in a GUI (swing) - this is called my RasterDisplay class. However, I am now creating another part of the GUI which will have a button that makes a new RasterDisplay. However, when I try and call my RasterDisplay constructor from within my actionPerformed method (see below) It tells me I have an "unhandled Exception type Exception". I can't throw Exception in the actionPerformed method so how do I get this method to work? Any help would be greatly appreciated - I am a total newcomer to Java and can't make head nor tail of related topics in all the forums...
    Cheers!
    import javax.swing.*;
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.event.*;
    public class RasterToolbar extends JFrame implements ActionListener{
         JButton open;
         public static void main(String[] args) throws Exception{
              new RasterToolbar();
         //method to make display panel with buttons
         public RasterToolbar()throws Exception{
                   super("Raster Viewer 1.0 beta");
                   setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
                   Container contentPane = getContentPane();
                   JPanel p1 = new JPanel();
                   p1.setLayout(new FlowLayout());
                   p1.setBorder(BorderFactory.createEmptyBorder(4,4,4,4));
                   open = new JButton("Open Viewer");
                   p1.add(open);
                   contentPane.add(p1,BorderLayout.WEST);
                   open.addActionListener(this);
                   pack();
                   setVisible(true);
         public void actionPerformed(ActionEvent ev){
         if(ev.getSource()== open){
              System.out.println("Open pressed");
              RasterDisplay viewer = new RasterDisplay(); // HERE IS THE PROBLEM LINE!
    }

    public void actionPerformed(ActionEvent ev){
         if(ev.getSource()== open){
              System.out.println("Open pressed");
              try {
                   RasterDisplay viewer = new RasterDisplay(); // HERE IS THE PROBLEM LINE!
              } catch(Exception e) {
                   // do what ever you want here!
                   e.printStackTrace();
    }

  • RAISERROR with Try/Catch does not exit after exception in catch block

    I am trying to propogate an error from within my proc out to the caller.
    In the attached example I have 2 sets of try catch blocks.
    I raiserror in the first
    catch the error and then raiserror again. (I expect to exit)
    I do not expect :
    to get to print 'post test'
    to get to second try block.
    but this does not exit, instead the code flows as per 2 runs.
    I do not understand the reason for the flows, as it seems counterintuitive to be raising an error but then still print following exceptions. I cannot seem to find any references that explains this behaviour.
     running tests together results
    print '-------------------------------------------------------'
    print 'test 15'
    exec test_raiseerror 15
    print '-------------------------------------------------------'
    print 'test 16'
    exec test_raiseerror 16
    print '-------------------------------------------------------'
    print 'test 17'
    exec test_raiseerror 17
    print '-------------------------------------------------------'
    print 'test 18'
    exec test_raiseerror 18
    print '-------------------------------------------------------'
    'RESULTS'
    test 15
    error number provided: 15
    Msg 50000, Level 15, State 1, Procedure test_raiseerror, Line 21
    name hello 15
    post test
    15
    Msg 50000, Level 15, State 1, Procedure test_raiseerror, Line 37
    name hello 2 15
    post test2
    test 16
    error number provided: 16
    Msg 50000, Level 16, State 1, Procedure test_raiseerror, Line 21
    name hello 16
    post test
    16
    Msg 50000, Level 16, State 1, Procedure test_raiseerror, Line 37
    name hello 2 16
    post test2
    test 17
    error number provided: 17
    post test
    17
    post test2
    test 18
    error number provided: 18
    post test
    18
    post test2
    Msg 50000, Level 17, State 1, Procedure test_raiseerror, Line 21
    name hello 17
    Msg 50000, Level 17, State 1, Procedure test_raiseerror, Line 37
    name hello 2 17
    Msg 50000, Level 18, State 1, Procedure test_raiseerror, Line 21
    name hello 18
    Msg 50000, Level 18, State 1, Procedure test_raiseerror, Line 37
    name hello 2 18
    run tests seperately
    exec test_raiseerror 15
    error number provided: 15
    RESULTS 15
    Msg 50000, Level 15, State 1, Procedure test_raiseerror, Line 21
    name hello 15
    post test
    15
    Msg 50000, Level 15, State 1, Procedure test_raiseerror, Line 37
    name hello 2 15
    post test2
    exec test_raiseerror 16
    RESULTS 16
    error number provided: 16
    Msg 50000, Level 16, State 1, Procedure test_raiseerror, Line 21
    name hello 16
    post test
    16
    Msg 50000, Level 16, State 1, Procedure test_raiseerror, Line 37
    name hello 2 16
    post test2
    exec test_raiseerror 17
    RESULTS 17
    error number provided: 17
    post test
    17
    post test2
    Msg 50000, Level 17, State 1, Procedure test_raiseerror, Line 21
    name hello 17
    Msg 50000, Level 17, State 1, Procedure test_raiseerror, Line 37
    name hello 2 17
    exec test_raiseerror 18
    RESULTS 18
    error number provided: 18
    post test
    18
    post test2
    Msg 50000, Level 18, State 1, Procedure test_raiseerror, Line 21
    name hello 18
    Msg 50000, Level 18, State 1, Procedure test_raiseerror, Line 37
    name hello 2 18
     CODEBLOCK:
    if object_id('test_raiseerror','P') is not null
    drop proc test_raiseerror
    go
    create proc test_raiseerror(@id as int) as
    begin
    begin try
    declare @name varchar(20)
    select @name = 'hello'
    raiserror('name %s %d',@id,1,@name,@id)
    print 'next'
    end try
    begin catch
    declare @errormessage nvarchar(4000)
    declare @errornum int
    select @errormessage = error_message()
    , @errornum = error_severity()
    print 'error number provided: ' + convert(varchar(2),@errornum)
    raiserror(@errormessage, @errornum,1)
    print 'post test'
    end catch
    begin try
    select @name = 'hello 2'
    raiserror('name %s %d', @id,1,@name, @id)
    end try
    begin catch
    select @errormessage = error_message()
    , @errornum = error_severity()
    print @errornum
    raiserror(@errormessage, @errornum,1)
    print 'post test2'
    end catch
    end
    go
    sqlserver 2008 & 2008 R2

    There is a Connect that describes a similiar complaint.  But basically a raiserror inside a catch block does not terminate the procedure, it will continue with any additional code in the CATCH and FINALLY unless it hits a return statement.
    http://connect.microsoft.com/SQLServer/feedback/details/275308/have-raiserror-work-with-xact-abort

  • Oracle JSP Exception code too large for try block

    My jsp is exceeding the memory limit (64KB for Oracle 10g App server i think its the JVM limit),
    so it is throwing exception ,code too large for try block,how to over come this,I cant minimize the use of logic tags because it is business requirement.please help me out.

    I think you need to give a value to the attribute buffer in the <%@ page%> directive to solve the problem.
    There will not be any need of going for pagination then.
    buffer="none | 8kb | sizekb"The buffer size in kilobytes used by the out object to handle output sent from the compiled JSP page to the client Web browser. The default value is 8kb. If you specify a buffer size, the output is buffered with at least the size you specified.
    check the documentation at
    http://java.sun.com/products/jsp/tags/11/syntaxref11.fm7.html
    Uday

  • I can throw exception from a catch

    Hello,
    I have created a new Exception : myException (for example).
    and, i can't throw it under a catch bloc !!
    My code :
    public myMethod( ... ) throw myException {
         try {
              if(true) thorw new NullPointerException("test nll pt");
         } catch(NullPointerException nullPt) {
              if(true) throw new myException("toto",nullPt.getMessage());
    this code doesn't want to throw "myException" from the "catch" !
    Why ?
    myException extends the class Exception.
    Thanks.
    maxx.

    First, I assume you didn't cut and paste the code, as what you have there won't compile. Can you 1) paste the actual code and 2) be a bit more specific about what's happening?
    Aside from a couple of misspellings, I don't see why it wouldn't throw myException. Is it not compiling? Running but not throwing any exception? Throwing a different exception?

  • Constructor can throw exception or Not ?

    Anybody please tell me if the constructor throws an exception or not ?
    Please reply soon
    Thanks
    Amitindia

    A constructor can throw an Exception. However I
    would suggest throwing the generic Throwable, Error,
    Exception or RuntimeException rather than a specific
    exception is bad practice and you should choose an
    appropirate exception to throw.All depends on wich kind of exception you are throwing,checked or unchecked. It's an even worse form to throw a RE, Error, or Throwable when you are throwing in fact a checked exception.
    Nevertheless, I do agree, you must always strive to not throw exceptions, of any kind, in your construtor code. Construtors should be simple and reliable. Unles you have a very compelling reason to not do it, try to isolate the risky parts of the code where they are called ofter object construction or class loading.
    May the code be with you.

Maybe you are looking for