I have a separate JAR library with a collection of methods that throw custom exceptions, for example:
public String methodName() throws CustomException {
// code here
}
I then add the JAR to the classpath and reference the library method within a try statement in source code:
try {
DemoClass demoClass = new DemoClass ();
demoClass.methodName() // this should throw a CustomException if something occurs
} catch (CustomException e) {
// something here
}
The above code snippet keeps returning the following compilation error:
CustomException is never thrown in the body of corresponding try statement
If the method is in the local context (not packaged in a JAR) the code works.. So my question, is it possible to “throw” custom exceptions from JAR libraries?
It doesn’t really matter whether the your class is in a jar or in the local context, it can always throw exceptions. You should check if you are using the class and calling the method that you intend to and not some other class and some other method with same name.
My hunch is something like
ParseExceptionwhich is in bothjava.text.ParseExceptionand inorg.apache.commons.cli.ParseExceptionand whendemoClass.methodName()actually throws the former, you would have imported the latter in your code and trying to catch it and that is what the compiler is complaining about. You may want to check all the locations where the CustomException is present and you are trying to catch the right one.