Java Reference
In-Depth Information
public static void methodA()
{
try
{
methodB();
}
catch (Exception e)
{
System.out.println(e.toString() + " caught in methodA");
e.printStackTrace();
}
}
public static void methodB() throws Exception
{
methodC();
}
public static void methodC() throws Exception
{
throw new Exception("Exception generated in method C");
}
}
Sample Run:
java.lang.Exception: Exception generated in method C caught in methodA
java.lang.Exception: Exception generated in method C
at PrintStackTraceExample2.methodC(PrintStackTraceExample2.java:30)
at PrintStackTraceExample2.methodB(PrintStackTraceExample2.java:25)
at PrintStackTraceExample2.methodA(PrintStackTraceExample2.java:14)
at PrintStackTraceExample2.main(PrintStackTraceExample2.java:7)
1
1
Exception-Handling Techniques
When an exception occurs in a program, usually the programmer has three choices—
terminate the program, fix the error and continue, or log the error and continue. The
following sections discuss each situation.
Terminate the Program
In some cases, it is best to let the program terminate when an exception occurs. Suppose
you have written a program that inputs data from a file. If the input file does not exist
when the program executes, then there is no point in continuing with the program. In
this case, the program can output an appropriate error message and terminate.
 
 
Search WWH ::




Custom Search