Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception Q

 
Kedar Dravid
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please use tags around your code. Thanks

Also the code does not compile.
[ February 28, 2005: Message edited by: Barry Gaunt ]
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By handling, it means catching the exception using try/catch statement.



Joyce
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic