0

I am trying to create a program where I want to input the spring configurations file from user just to create some demo application. If I directly call new ClassPathXmlApplicationContext(filePath), it throws FileNotFoundException if the file doesn't exist.

I want to catch this exception and display the user an error message instead of terminating the application. Even if I surround the call to constructor by try-catch or using throws declaration, the exception is not caught and the application terminates printing the stack trace.

Any ideas how can I catch the thrown exception? This is a Spring MVC application

The caller function (Inside the @Controller class)-

private String getFlavours(ModelMap model, String configFile) {
    FlavourService flavourService = new FlavourService();
    String results = null;

    try {
        results = flavourService.generateFlavour(configFile);
    } catch (FileNotFoundException e) {
        System.out.println("In FNF Execp");
        model.addAttribute("errorMessage", "Requested configurations file not found");
        return "index";
    }

    model.addAttribute("results", results);
    model.addAttribute("configFile", configFile);
    return "springDemo";
}

The called function (Inside other normal class FlavourService from different package)-

public String generateFlavour(String configFile) throws FileNotFoundException {
    String path = "somepath"; //this is path from classpath
    String filename = configFile;

    context = new ClassPathXmlApplicationContext(path + filename);

    //code to generate required output

    return output;
}

I am getting the exception as -

SEVERE: Servlet.service() for servlet HelloWeb threw exception
java.io.FileNotFoundException: class path resource [com/cts/spring/config/dsf] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:158)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:329)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:303)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:216)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:187)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:251)
    at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:127)
    at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:93)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:540)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:454)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at com.cts.spring.FlavourService.generateFlavour(FlavourService.java:31)
    at com.cts.spring.controller.SpringFlavoursController.getFlavours(SpringFlavoursController.java:38)
    at com.cts.spring.controller.SpringFlavoursController.viewFlavours(SpringFlavoursController.java:30)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:243)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:201)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:163)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:108)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:402)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:249)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:267)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:245)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:260)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

If I try creating a similar problem in Java Project using spring only, I get a different exception where it mentions that FileNotFoundException is nested exception as follows -

Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [dsf]; nested exception is java.io.FileNotFoundException: class path resource [dsf] cannot be opened because it does not exist
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:343)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:303)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:216)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:187)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:251)
    at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:127)
    at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:93)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:540)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:454)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at MainApp.main(MainApp.java:16)
Caused by: java.io.FileNotFoundException: class path resource [dsf] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:158)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:329)
    ... 13 more
Mukund Jalan
  • 1,145
  • 20
  • 39
  • Clearly, it is not throwing a FileNotFoundException, so of course you can not catch it. – Raedwald Mar 12 '15 at 09:46
  • @Raedwald as you can see in the first case (my actual application) its showing `FileNotFoundException` In the later case I got to know that its an nested exception. How can i deal with that??? Because I don't want to mess exception handling by just taking some superclass of exception to handle a nested exception – Mukund Jalan Mar 12 '15 at 14:09
  • See also http://stackoverflow.com/questions/7593535/how-to-catch-a-nested-exception-in-java – Raedwald Mar 13 '15 at 09:50

2 Answers2

1
  • Use a higher level of Exception for catching, say IOException. It might so happen that you are catching only FileNotFoundException and there might be other type of exception spring might be throwing.
  • use FileSystemXmlApplicationContext instead, to pass FileSystem paths as parameters.

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/support/FileSystemXmlApplicationContext.html#FileSystemXmlApplicationContext-java.lang.String-

prasad vsv
  • 1,138
  • 8
  • 10
  • thanks for the idea. It didn't work for `IOException` but worked for `Exception` like a charm. It is giving me an nested exception of `FileNotFoundException`. I want to know, how can I catch the nested exception only because catching exception of type `Exception` may not be effective if some other exception is thrown by the code due to some other reason. – Mukund Jalan Mar 12 '15 at 05:46
0

Create a new File Object before passing the file Path in Constructor and check that file actually exist or not

Try This

File file=new File(filePath);
if(!file.exists) // Check if file Actually Exists or not 
 //thow any Exception if file Not Exists
Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62
  • this is a good idea to deal with the problem (maybe good for real-time applications), but as I am learning the concepts in Java, I want know how the exception can be handled rather than finding an alternative approach to the problem. – Mukund Jalan Mar 12 '15 at 05:49
  • This is not an alternative approach , what would be your first attempt after getting `FileNotFound Exception` ? you will either create that file or just Quit , which you can do from here also . – Neeraj Jain Mar 12 '15 at 05:54