为了账号安全,请及时绑定邮箱和手机立即绑定

当我试图编译我的Java代码时,为什么我会得到“异常;必须被捕获或声明为被抛出”?

当我试图编译我的Java代码时,为什么我会得到“异常;必须被捕获或声明为被抛出”?

胡说叔叔 2019-07-12 15:04:55
当我试图编译我的Java代码时,为什么我会得到“异常;必须被捕获或声明为被抛出”?考虑:import java.awt.*;import javax.swing.*;import java.awt.event.*;import javax.crypto.*;import javax.crypto.spec.*;import java.security.*; import java.io.*;public class EncryptURL extends JApplet implements ActionListener {     Container content;     JTextField userName = new JTextField();     JTextField firstName = new JTextField();     JTextField lastName = new JTextField();     JTextField email = new JTextField();     JTextField phone = new JTextField();     JTextField heartbeatID = new JTextField();     JTextField regionCode = new JTextField();     JTextField retRegionCode = new JTextField();     JTextField encryptedTextField = new JTextField();     JPanel finishPanel = new JPanel();     public void init() {         //setTitle("Book - E Project");         setSize(800, 600);         content = getContentPane();         content.setBackground(Color.yellow);         content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));         JButton submit = new JButton("Submit");         content.add(new JLabel("User Name"));         content.add(userName);         content.add(new JLabel("First Name"));         content.add(firstName);         content.add(new JLabel("Last Name"));         content.add(lastName);         content.add(new JLabel("Email"));         content.add(email);         content.add(new JLabel("Phone"));         content.add(phone);         content.add(new JLabel("HeartBeatID"));         content.add(heartbeatID);         content.add(new JLabel("Region Code"));         content.add(regionCode);         content.add(new JLabel("RetRegionCode"));         content.add(retRegionCode);         content.add(submit);         submit.addActionListener(this);     } }我得到了一个未报告的例外:java.lang.Exception; must be caught or declared to be thrownbyte[] encrypted = encrypt(concatURL);以及:.java:109: missing return statement如何解决这些问题?
查看完整描述

3 回答

?
宝慕林4294392

TA贡献2021条经验 获得超8个赞

问题在于这种方法:

  public static byte[] encrypt(String toEncrypt) throws Exception{

这是方法签名上面写着:

  • 方法名称是:

    加密

  • 它接收什么参数:一个名为

    图恩密特

  • 其访问修饰符:

    公共静电

  • 如果可能的话

    抛出

    调用时的异常。

在这种情况下,方法签名表明,当调用该方法时,“可能会”抛出类型为“Exception”的异常。

    ....
    concatURL = padString(concatURL, ' ', 16);
    byte[] encrypted = encrypt(concatURL); <-- HERE!!!!!
    String encryptedString = bytesToHex(encrypted);
    content.removeAll();
    ......

所以编译器是这样说的:要么用try/catch构造包围它,要么声明方法(在其中使用)抛出“Exception”它Self。

真正的问题是“加密”方法定义。任何方法都不应该返回“异常”,因为它太泛化了,并且可能隐藏其他一些。例外类型最好是有一个具体的例外。

试试这个:

public static byte[] encrypt(String toEncrypt) {
    try{
      String plaintext = toEncrypt;
      String key = "01234567890abcde";
      String iv = "fedcba9876543210";

      SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
      IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

      Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
      cipher.init(Cipher.ENCRYPT_MODE,keyspec,ivspec);
      byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());

      return encrypted;
    } catch ( NoSuchAlgorithmException nsae ) { 
        // What can you do if the algorithm doesn't exists??
        // this usually won't happen because you would test 
        // your code before shipping. 
        // So in this case is ok to transform to another kind 
        throw new IllegalStateException( nsae );
    } catch ( NoSuchPaddingException nspe ) { 
       // What can you do when there is no such padding ( whatever that means ) ??
       // I guess not much, in either case you won't be able to encrypt the given string
        throw new IllegalStateException( nsae );
    }
    // line 109 won't say it needs a return anymore.
  }

基本上,在这种特殊情况下,您应该确保密码包在系统中可用。

Java需要对加密包进行扩展,因此,异常被声明为“检查”异常。让你在他们不在场的时候处理。

在这个小程序中,如果密码包不可用,您就不能做任何事情,所以您可以在“开发”时检查它。如果程序运行时抛出这些异常是因为您在“开发”中做错了什么,那么RuntimeException子类更合适。

最后一行不再需要返回语句了,在第一个版本中,您捕获了异常而对其不做任何操作,这是错误的。

try { 
    // risky code ... } catch( Exception e ) { 
    // a bomb has just exploited
    // you should NOT ignore it } // The code continues here, but what should it do???

如果代码要失败,最好是快速失败

以下是一些相关的答案:


查看完整回答
反对 回复 2019-07-12
?
慕斯王

TA贡献1864条经验 获得超2个赞

第一个错误

异常;必须捕获或声明为抛出字节[]加密=加密(串联URL);

意味着你的encrypt方法引发未由actionPerformed方法调用它。在Java异常教程.

您可以从中选择几个选项来编译代码。

  • 你可以移除

    throws Exception

    从你的

    encrypt

    方法和

    实际手柄

    内部异常

    encrypt.

  • 可以从

    encrypt

    加上

    throws Exception

    的异常处理块

    actionPerformed

    方法。

通常最好在最低级别处理异常,而不是将其传递到更高的级别。

第二个错误只意味着您需要向包含第109行的任何方法中添加一个返回语句(也是encrypt,在这种情况下)。方法中有返回语句,但如果抛出异常,则可能无法到达异常,因此需要在CATCH块中返回,或者从encrypt就像我之前提到的。


查看完整回答
反对 回复 2019-07-12
  • 3 回答
  • 0 关注
  • 971 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号