This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception

 
Alpana Singh
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Except extends Exception{}
public class Q48
{
public static void main(String[]args)
{
try
{
System.out.println(10/0);
}
catch(Except e)
{
System.out.println("catch block");
}
}
}


Why does this code gives a compiler error,"Except is nit thrown in try block".the statement 10/0 gives an arithmetic exception.Right?

Please help.
 
Ray Horn
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Right, it gives arithmetic exception, but you are trying to catch 'Except', which is not being thrown in the try block. Thus the compile error. Change to:

try {
System.out.println(10/0);
} catch(ArithmeticException e) {
System.out.println("catch block");
}
 
Alpana Singh
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So it's like ,if an exception is not thrown in the try block and we try to catch that then it will give compiler error.

Am i right?
 
Ray Horn
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes with the additional note that you can have 'catch (Exception e)' and there would not be a compile error.
[ November 01, 2005: Message edited by: Ray Horn ]
 
Rob Spoor
Sheriff
Pie
Posts: 20550
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Alpana Singh:
So it's like ,if an exception is not thrown in the try block and we try to catch that then it will give compiler error.

Am i right?

Only for checked exceptions (i.e., exceptions that are not subclasses of RuntimeException).
[ November 01, 2005: Message edited by: Rob Spoor ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic