javac编译时,提示如下:
Test.java:40: unreported exception org.apache.commons.fileupload.FileUploadExcep
tion; must be caught or declared to be thrown
List items = sfu.parseRequest(req);
^
1 error
代码如下:
package mytest;
import java.io.IOException;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Iterator;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
//import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class Test extends HttpServlet {
static final long serialVersionUID = 1L;
private String fileExt(String fileName)
{
return fileName.substring(fileName.lastIndexOf(".") + 1);
}
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
req.setCharacterEncoding("UTF-8");
/*
HttpSession sess = reg.getSession();
String uid = (String)sess.getAttribute("uid");
*/
FileItemFactory fif = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(fif);
List items = sfu.parseRequest(req); //here is line 40
Iterator iter = items.iterator();
FileItem item = null;
HashMap<String, String> data = new HashMap<String, String>();
while(iter.hasNext()) {
item = (FileItem)iter.next();
if(item.isFormField())
data.put(item.getFieldName(), item.getString("UTF-8"));
else {
FileOutputStream fos = new FileOutputStream("C:\\Users\\my\\9." + fileExt(item.getName()));
fos.write(item.get());
fos.flush();
fos.close();
}
}
data.clear();
}
}
我没有try-catch。我的疑问是,为什么会有exception?怎么解决?
谢谢大家!
------解决方案--------------------
你写的有问题,当然报异常了,你把完整的异常信息贴出来吧。。。。。
------解决方案--------------------
把异常信息贴出来吧!!!!!
------解决方案--------------------
List items = sfu.parseRequest(req);
必须捕获异常。
你捕获下异常应该就没问题了
------解决方案--------------------
List items=null;
try {
items = sfu.parseRequest(req);
} catch (FileUploadException e) {
// TODO 这里根据自己的需求进行处理,可以为空(不建议)
e.printStackTrace();
}
不建议采用 System.out.println(ex.getMessage())
可以使用 e.printStackTrace();
------解决方案--------------------
可以thows异常 也可以捕获下异常 它就是提示你这里必须要thows或者捕获异常