java error unreported exception java.lang.Exception;必须被抓住或宣布被抛出

时间:2011-01-27 08:20:25

标签: java

import java.io.FileInputStream; 

import org.apache.commons.codec.binary.Base64;

public class Encode 
{

    //file path ex : C:\Program Files\Cordys\Web\reports\I0001180.pdf
    public static String encodeFileStream(String filePath) throws Exception 
    {    

        StringBuffer sb=new StringBuffer();

        try 
        {

            FileInputStream fin = new FileInputStream(filePath);
            //StringBuffer sb=new StringBuffer();
            int lineLength = 72;
            byte[] buf = new byte[lineLength/4*3];

            while (true) 
            {
                int len = fin.read(buf);
                if (len <= 0)
                {
                    break;
                }
                //new Base64().encode(byte);
                //sb.append(Base64.encode(buf));
                //sb.append(Base64.encodeBase64(buf));

                Base64 b = new Base64();
                sb.append(b.encode(buf)); 

                //return sb.toString();
            }
        }  

        catch(Exception e) 
        {
            return e.getMessage();
        }

        return sb.toString();
    }

    public static void main(String args[])
    {
        String s="";

        s=encodeFileStream("E:/CSSDocument/Test.pdf");
    }   
}

2 个答案:

答案 0 :(得分:2)

您的方法“encodeFileStream”会抛出异常。您正在使用该方法捕获它,因此您不需要在方法声明中声明它。

或者:

  1. 从encodeFileStream的声明中删除“throws Exception”,或
  2. 将“throws Exception”添加到main(String [] args)
  3. 的声明中

答案 1 :(得分:0)

您没有捕获encodeFileStream()可能引发的异常:

public static void main(String args[]) throws Exception{
    String s="";
    s=encodeFileStream("E:/CSSDocument/Test.pdf");
}

会有所帮助,但这不是我称之为“良好的异常处理”。

相关问题