permaculture playing cards*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Exception" Watch "Exception" New topic
Author

Exception

Alpana Singh
Ranch Hand

Joined: Sep 27, 2005
Posts: 36
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

Joined: Oct 20, 2005
Posts: 39
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

Joined: Sep 27, 2005
Posts: 36
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

Joined: Oct 20, 2005
Posts: 39
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

Joined: Oct 27, 2005
Posts: 19697
    
  20

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 ]

SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
wood burning stoves
 
subject: Exception