java - 当我尝试编译我的 Java 代码时,为什么会得到 "Exception; must be caught or declared to be thrown"?

标签 java exception

考虑:

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


    public void actionPerformed(ActionEvent e) {

        if (e.getActionCommand() == "Submit"){

            String subUserName = userName.getText();
            String subFName = firstName.getText();
            String subLName = lastName.getText();
            String subEmail = email.getText();
            String subPhone = phone.getText();
            String subHeartbeatID = heartbeatID.getText();
            String subRegionCode = regionCode.getText();
            String subRetRegionCode = retRegionCode.getText();

            String concatURL =
                "user=" + subUserName + "&f=" + subFName +
                "&l=" + subLName + "&em=" + subEmail +
                "&p=" + subPhone + "&h=" + subHeartbeatID +
                "&re=" + subRegionCode + "&ret=" + subRetRegionCode;

            concatURL = padString(concatURL, ' ', 16);
            byte[] encrypted = encrypt(concatURL);
            String encryptedString = bytesToHex(encrypted);
            content.removeAll();
            content.add(new JLabel("Concatenated User Input -->" + concatURL));

            content.add(encryptedTextField);
            setContentPane(content);
        }
    }

    public static byte[] encrypt(String toEncrypt) throws Exception{
        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(Exception e){
        }
    }


    public static byte[] decrypt(byte[] toDecrypt) throws Exception{
        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.DECRYPT_MODE, keyspec, ivspec);
        byte[] decrypted = cipher.doFinal(toDecrypt);

        return decrypted;
    }


    public static String bytesToHex(byte[] data) {
        if (data == null)
        {
            return null;
        }
        else
        {
            int len = data.length;
            String str = "";
            for (int i=0; i<len; i++)
            {
                if ((data[i]&0xFF) < 16)
                    str = str + "0" + java.lang.Integer.toHexString(data[i]&0xFF);
                else
                    str = str + java.lang.Integer.toHexString(data[i]&0xFF);
            }
            return str;
        }
    }


    public static String padString(String source, char paddingChar, int size)
    {
        int padLength = size-source.length() % size;
        for (int i = 0; i < padLength; i++) {
            source += paddingChar;
        }
        return source;
    }
}

我收到一个未报告的异常:

java.lang.Exception; must be caught or declared to be thrown
byte[] encrypted = encrypt(concatURL);

还有:

.java:109: missing return statement

我该如何解决这些问题?

最佳答案

你所有的问题都源于此

byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());
return encrypted;

包含在 try、catch block 中的问题是,如果程序发现异常,您不会返回任何内容。像这样写(根据你的程序逻辑修改它):

public static byte[] encrypt(String toEncrypt) throws Exception{
    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(Exception e){
        return null;            // Always must return something
    }
}

对于第二个,您必须从 encrypt 方法调用中捕获异常,如下所示(也可以根据您的程序逻辑对其进行修改):

public void actionPerformed(ActionEvent e)
  .
  .
  .
    try {
        byte[] encrypted = encrypt(concatURL);
        String encryptedString = bytesToHex(encrypted);
        content.removeAll();
        content.add(new JLabel("Concatenated User Input -->" + concatURL));

        content.add(encryptedTextField);
    setContentPane(content);
    } catch (Exception exc) {
        // TODO: handle exception
    }
}

你必须从中吸取的教训:

  • 具有返回类型的方法必须始终返回该类型的对象,我的意思是在所有可能的情况下
  • 必须始终处理所有已检查的异常

关于java - 当我尝试编译我的 Java 代码时,为什么会得到 "Exception; must be caught or declared to be thrown"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/908672/

相关文章:

java - 有没有办法在重定向到错误页面(在 Java 中)之前捕获错误的堆栈跟踪?

java - 是否可以使用反射来获取具体的实现类型(例如 Class<? extends MyInterface>)?

java - 在 Java 中缩放图表以适合一个打印页面

c# - 发生异常时显示窗体 C#

Java GUI/Swing、停止线程、在类之间传递整数

java - 修改xml中特定标签的值

haskell - 如何在 Haskell 中实现生成 Maybe String 的 safeReadFile 函数

javascript - 异常在 JavaScript 中不起作用

java - 从 Throwable 获取根错误消息

php - Laravel 自定义异常配置