Exceptions

How can you handle an exception within a method, but still allow any calling methods to subsequently handle the exception as well?


(Submitted by Vivek Pabby)
The following piece of code would help:
// This is the calling method

public void yourCallingMethod() 
{

	// some code ........

	try {
	        yourCalledMethod();
	}
// This catch will catch the thrown exception from the called method

	catch (IOException e1) {
	        showStatus("Caught thrown Exception : " + e1.getMessage() );
	}
}

public void yourCalledMethod() 
{
//
// The following try/catch block will catch IOException and throw it again
//
	try {
	        DataInputStream din = new DataInputStream( 
	        new BufferedInputStream(socket.getInputStream()));
		DataOutputStream dout = new DataOutputStream(
	        new BufferedOutputStream(socket.getOutputStream()));
	}
	catch(IOException e) {
	        showStatus("Exception caught: " + e.getMessage() );
//
// By throwing the exceptiuon again, you can have the calling method catch it.
//
		throw e;
	}
}

How can you define range exceptions that protect all of your code?


(Submitted by Vivek Pabby)
Any code in a try-catch block will get the exceptions that happen in that block. If you put all your code in a main try-catch block you can get any "uncatched" exceptions from that code:

	try {
                // put all your code here
                // this code can also have its own try-catch blocks
                // making it a nested try-catch situation
                try {
                       //  more code .......
                } catch (anyExceptionYouLike e) {}
                // more code.......
	}
// This catch will catch any exceptions in all your blocked code which are not
// caught by any inner try-catch blocks
	catch (ArrayIndexOutOfBounds ex) {
	        showStatus("Exception : " + ex.getMessage() );
        }
	catch (IOException e1) {
	        showStatus("Exception : " + e1.getMessage() );
        } catch (Exception e2) { }
}
You can also create your own exceptions with custom messages and throw and catch them.