Exceptions

Exceptions

Its possible to print the stack trace without having an exception at all using

Thread.currentThread().dumpStack();

See, the relevant thread for more info here at JavaRanch -> http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=1&t=017844&p=1

try/catch/finally blocks

* You can have a try-finally block without having a catch block at all, provided you have a return statement in a finally block.

Check this program for example.

class FinallyWithReturnDemo {
    public void methodWithTryAndFinallyWithReturn() {
        try{
            throw new Exception();            
        }finally {
            System.out.println("I am in finally block!");
            return;
        }
    }
 
    /* Here you will get a compiler error */
    public void methodWithTryAndFinallyWithoutReturn() {
        try{
            throw new Exception();            
        }finally {
            System.out.println("I am in finally block!");
            //return;
        }
    }
}

Original question you can see in the link above of JavaRanch.

Explanation given by Alpesh Vesuwala:

Raghavan's point is right and I want to elaborate that,

1) If method returns nothing and if you throw an Exception in a try block that does not handle by the catch block and not even handle by the caller then compiler will raise an error stating unhandled exception.

2) If method returns some value and if you throw an Exception in a try block that does not handle by the catch block, you do not return any value in your finally block and not even handle by the caller then compiler will raise an error stating unhandled exception.

3) If method returns some value and if you throw an Exception in a try block that does not handle by the catch block and not even handle by the caller but this time you return some value from your finally block then compiler will acept the things knowing that error occurs or not finally block is going to execute anyhow and will return some value, so no point of handling the error and will result in the value return by the fianlly block.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.