thomas_ds
thomas_ds

Reputation:

Java exception handling - Custom exception

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?

Upvotes: 1

Views: 10115

Answers (4)

Markus Lausberg
Markus Lausberg

Reputation: 12257

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!

Upvotes: 9

Jon Skeet
Jon Skeet

Reputation: 1500595

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?

Upvotes: 3

Gregory Mostizky
Gregory Mostizky

Reputation: 7261

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.

Upvotes: 1

Laurence Gonsalves
Laurence Gonsalves

Reputation: 143154

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.)

Upvotes: 2

Related Questions