views:

1474

answers:

4

I have a custom exception like this

public class MyOwnException extends Exception {

}

Then in my class

I have two methods

public void ExceptionTest() throws Exception {
  throw new FileNotFoundException();
}


public void ApplicationExceptionTest() throws MyOwnException {
  throw new FileNotFoundException();
}

Eclipse complains about the second method 'Unhandled exception type FileNotFoundException'. I thought since MyOwnException extends Exception it shouldnt complain...

Can anyone tell me what I am missing here?

+3  A: 

Your method declares that it throws MyOwnException, but FileNotFoundException isn't a MyOwnException. Just because they both subclass Exception eventually doesn't mean they're related to each other.

You can only throw a checked exception if that exception class or a superclass is explicitly listed in the throws clause. MyOwnException isn't a superclass of FileNotFoundException.

Why do you want to do this?

Jon Skeet
+7  A: 

Extension tree

  • Exception
    • IOException
      • FileNotFoundException
    • MyOwnException

FileNotFound and MyOwn did not know each other.

public void ApplicationExceptionTest() throws Exception 
{ 
throw new FileNotFoundException(); 
}

is the way to go

Comment:

I hope this is for mockup testing only and not for implementing a class you wnt to use in your regular source code!

Markus Lausberg
+1 for showing the class hierarchy. @thomas_ds You mentioned you have Eclipse, so you can see this tree by right-clicking on MyOwnException and selecting "Open Type Hierarchy" or F4. In this case, both Exception and IOException have lots of other subclasses.
MatrixFrog
+2  A: 

You're saying that ApplicationExceptionTest throws MyOwnException. While MyOwnException extends Exception, that is irrelevant here because FileNotFoundException does not extend MyOwnException.

If it makes it easier, try replacing Exception with "Shape", FileNotFoundException with "Square" and MyOwnException with "Circle". So you're saying that you throw a Circle but you're actually throwing a Square. It doesn't matter that both are Shapes.

(As an aside, your naming convention is very atypical for Java. In Java, methods usually start with a lower-case letter.)

Laurence Gonsalves
A: 

Checked exceptions in Java are generally a bad idea, because too often it leads to 'exception spaghetti'. Most of the modern frameworks do not use checked exception - in fact, most of them wrap existing legacy checked exceptions with unchecked ones.

Gregory Mostizky