This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Exception Q Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Exception Q" Watch "Exception Q" New topic
Author

Exception Q

Kedar Dravid
Ranch Hand

Joined: May 28, 2004
Posts: 333
Consider the piece of code given below:

Output:
Computing average.
Finally done.
<Stack Trace is printed.>

My question: Why isn't the statement marked //2 part of the o/p, since the exception is handled by the default exception handler (the main() method) ?

[ February 28, 2005: Message edited by: Barry Gaunt ]
[ February 28, 2005: Message edited by: Kedar Dravid ]
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Please use tags around your code. Thanks

Also the code does not compile.
[ February 28, 2005: Message edited by: Barry Gaunt ]

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
main() is throwing the exceptiom, not handling it. The JVM is where the catching of the exception is done. Look at the stack trace carefully.
Veer Batra
Ranch Hand

Joined: Mar 12, 2001
Posts: 35
Your code has few problems, I don't know how you got this output.
1. It is not compiling as totalNumber is not defined, I think totalNumber should be replaced with totalAverage.
2. It is not handling ArithmeticException.

I have above changes to your code and now it gives your desired result. Here is the changed code :
public class Average
{
public static void main(String[] args)
{
printAverage(100, 0);
System.out.println("Exit main()."); //2
}

public static void printAverage(int totalSum, int totalAverage)
{
try
{
int average = computeAverage(totalSum, totalAverage);
System.out.println("Average = " + totalSum + " / " + totalAverage + " = " + average);
}
catch ( ArithmeticException a ) {}
finally
{
System.out.println("Finally done.");
}
System.out.println("Exit printAverage.");
}

public static int computeAverage(int sum, int number)
{
System.out.println("Computing average.");
return sum/number;
}
}


Regards,
Veer
Joyce Lee
Ranch Hand

Joined: Jul 11, 2003
Posts: 1392
By handling, it means catching the exception using try/catch statement.



Joyce
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Exception Q