java java错误未报告的异常java.lang.Exception; 必须被捕获或声明被抛出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4814068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 08:08:49  来源:igfitidea点击:

java error unreported exception java.lang.Exception; must be caught or declared to be thrown

java

提问by monika

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");
    }   
}

回答by Bringer128

Your method "encodeFileStream" throws Exception. You are catching it in that method so you don't need to declare it in your method declaration.

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

Either:

任何一个:

  1. Remove "throws Exception" from the declaration of encodeFileStream, or
  2. Add "throws Exception" to the declaration of main(String[] args)
  1. 从 encodeFileStream 的声明中删除“抛出异常”,或
  2. 在 main(String[] args) 的声明中添加“throws Exception”

回答by Christian Kuetbach

You don't catch the Exception, which may be thrown by encodeFileStream():

你没有捕捉到异常,它可能被抛出encodeFileStream()

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

would help, but this is not what I would call "Good exception handling".

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