Java Reference
In-Depth Information
You can redesign the m1() method to throw only one exception, say MyException , as follows:
public void m1() throws MyException {
try {
// Code for m1() method goes here
}
catch(Exception1 e1){
throw new MyException("Msg1", e1);
}
catch(Exception2 e2){
throw new MyException("Msg2", e1);
}
catch(Exception3 e3){
throw new MyException("Msg3", e1);
}
}
The redesigned method throws only one exception, which is of type MyException . The detailed message for
the exception is specific to the lower-level exception that is thrown and caught inside the method. The lower-level
exception is also propagated to the client as the cause of the higher-level exception. If the m1() method needs to throw
a new exception in the future, you can still fit the new exception in the old design. You need to add a catch block to
catch the new exception and rethrow MyException . This design keeps the throws clause of the m1() method stable.
It also allows for more exception types to be included in its body in future.
do not throw a generic exception from your method, such as Throwable , Exception , Error , RuntimeException ,
etc. do not specify a generic exception type in a catch block. the purpose of exception throwing or handling is to know
exactly the error condition that occurred and take appropriate action. it helps you to understand the cause of an error by
giving specific error messages to users. generating a specific error message is possible only when you handle exceptions
using specific exception types.
Tip
Accessing the Stack of a Thread
The stack is an area of memory that is used to store temporary data. It uses last-in, first-out (LIFO) style to add and
remove data. A stack resembles a stack in everyday life, such as a stack of topics. The bottom of the stack has the
first book that was placed on it. The top of the stack has the last book that was placed on it. When a book has to be
removed from the stack, the last book that was placed on the stack will be removed first. This is the reason a stack is
also called last-in, first-out memory. Figure 9-4 shows the arrangement of a stack.
Top of stack
Pop
Push
Book-3
Book-2
Book-1
Figure 9-4. Memory arrangement in a stack
 
 
Search WWH ::




Custom Search