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

时间:2021-07-16 23:40:24

Consider:

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

I'm getting an unreported exception:

我收到一个未报告的例外:

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

As well as:

以及:

.java:109: missing return statement

How do I solve these problems?

我该如何解决这些问题?

6 个解决方案

#1


27  

All your problems derive from this

你所有的问题都源于此

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

Which are enclosed in a try, catch block, the problem is that in case the program found an exception you are not returning anything. Put it like this (modify it as your program logic stands):

其中包含在try,catch块中,问题是如果程序发现异常,则不返回任何内容。像这样(将其修改为程序逻辑):

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

For the second one you must catch the Exception from the encrypt method call, like this (also modify it as your program logic stands):

对于第二个,您必须从加密方法调用中捕获异常,如下所示(也可以将其修改为程序逻辑):

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

The lessons you must learn from this:

你必须从中吸取教训:

  • A method with a return-type must always return an object of that type, I mean in all possible scenarios
  • 具有返回类型的方法必须始终返回该类型的对象,我的意思是在所有可能的场景中

  • All checked exceptions must always be handled
  • 必须始终处理所有已检查的异常

#2


5  

The problem is in this method:

问题出在这个方法中:

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

This is the method signature which pretty much says:

这是方法签名,几乎说:

  • what the method name is: encrypt
  • 方法名称是什么:加密

  • what parameter it receives: a String named toEncrypt
  • 它接收的参数是什么:名为toEncrypt的String

  • its access modifier: public static
  • 其访问修饰符:public static

  • and if it may or not throw an exception when invoked.
  • 如果在调用时可能抛出异常。

In this case the method signature says that when invoked this method "could" potentially throw an exception of type "Exception".

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

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

So the compilers is saying: Either you surround that with a try/catch construct or you declare the method ( where is being used ) to throw "Exception" it self.

因此编译器会说:要么用try / catch构造包围它,要么声明方法(正在使用的地方)自己抛出“Exception”。

The real problem is the "encrypt" method definition. No method should ever return "Exception", because it is too generic and may hide some other kinds of exception better is to have an specific exception.

真正的问题是“加密”方法定义。没有方法应该返回“异常”,因为它太通用了,可能隐藏其他类型的异常更好的是有一个特定的异常。

Try this:

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.
  }

Basically in this particular case you should make sure the cryptography package is available in the system.

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

Java needs an extension for the cryptography package, so, the exceptions are declared as "checked" exceptions. For you to handle when they are not present.

Java需要加密包的扩展,因此,异常被声明为“已检查”的异常。当你不在场时你可以处理。

In this small program you cannot do anything if the cryptography package is not available, so you check that at "development" time. If those exceptions are thrown when your program is running is because you did something wrong in "development" thus a RuntimeException subclass is more appropriate.

在这个小程序中,如果加密包不可用,则无法执行任何操作,因此请在“开发”时检查该程序。如果在程序运行时抛出这些异常是因为你在“开发”中做错了,那么RuntimeException子类更合适。

The last line don't need a return statement anymore, in the first version you were catching the exception and doing nothing with it, that's wrong.

最后一行不再需要return语句,在第一个版本中你捕获异常而对它一无所知,这是错误的。

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???

If the code is to fail, it is better to Fail fast

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

Here are some related answers:

以下是一些相关的答案:

#3


3  

The first error

第一个错误

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

java.lang.Exception的;必须被捕获或声明被抛出byte [] encrypted = encrypt(concatURL);

means that your encrypt method throws an exception that is not being handled or declared by the actionPerformed method where you are calling it. Read all about it at the Java Exceptions Tutorial.

表示您的encrypt方法抛出一个异常,该异常未被您调用它的actionPerformed方法处理或声明。阅读Java Exceptions Tutorial中的所有相关内容。

You have a couple of choices that you can pick from to get the code to compile.

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

  • You can remove throws Exception from your encrypt method and actually handle the exception inside encrypt.
  • 您可以从加密方法中删除throws Exception,并实际处理加密内部的异常。

  • You can remove the try/catch block from encrypt and add throws Exception and the exception handling block to your actionPerformed method.
  • 您可以从encrypt中删除try / catch块,并向您的actionPerformed方法添加throws Exception和异常处理块。

It's generally better to handle an exception at the lowest level that you can, instead of passing it up to a higher level.

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

The second error just means that you need to add a return statement to whichever method contains line 109 (also encrypt, in this case). There is a return statement in the method, but if an exception is thrown it might not be reached, so you either need to return in the catch block, or remove the try/catch from encrypt, as I mentioned before.

第二个错误只是意味着您需要将return语句添加到包含第109行的任何方法(在这种情况下也加密)。方法中有一个return语句,但如果抛出异常,则可能无法访问,因此您需要返回catch块,或者从encrypt中删除try / catch,如前所述。

#4


1  

You'll need to decide how you'd like to handle exceptions thrown by the encrypt method.

您需要决定如何处理encrypt方法抛出的异常。

Currently, encrypt is declared with throws Exception - however, in the body of the method, exceptions are caught in a try/catch block. I recommend you either:

目前,使用throws Exception声明encrypt - 但是,在方法的主体中,异常会在try / catch块中捕获。我推荐你:

  • remove the throws Exception clause from encrypt and handle exceptions internally (consider writing a log message at the very least); or,
  • 从加密中删除throws Exception子句并在内部处理异常(考虑至少写一条日志消息);要么,

  • remove the try/catch block from the body of encrypt, and surround the call to encrypt with a try/catch instead (i.e. in actionPerformed).
  • 从加密体中删除try / catch块,并用try / catch代替加密调用(即在actionPerformed中)。

Regarding the compilation error you refer to: if an exception was thrown in the try block of encrypt, nothing gets returned after the catch block finishes. You could address this by initially declaring the return value as null:

关于编译错误,请参考:如果在加密的try块中抛出异常,则在catch块完成后不会返回任何内容。您可以通过最初将返回值声明为null来解决此问题:

public static byte[] encrypt(String toEncrypt) throws Exception{
  byte[] encrypted = null;
  try {
    // ...
    encrypted = ...
  }
  catch(Exception e){
    // ...
  }
  return encrypted;
}

However, if you can correct the bigger issue (the exception-handling strategy), this problem will take care of itself - particularly if you choose the second option I've suggested.

但是,如果您可以纠正更大的问题(异常处理策略),这个问题将自行处理 - 特别是如果您选择我建议的第二个选项。

#5


0  

In your 'encrypt' method, you should either get rid of the try/catch and instead add a try/catch around where you call encrypt (inside 'actionPerformed') or return null inside the catch within encrypt (that's the second error.

在你的'encrypt'方法中,你应该摆脱try / catch,而是在你调用encrypt(在'actionPerformed'内)的地方添加一个try / catch,或者在encrypt中的catch内返回null(这是第二个错误。

#6


0  

In actionPerformed(ActionEvent e) you call encrypt(), which is declared to throw Exception. However, actionPerformed neither catches this Exception (with try/catch around the call to encrypt()) nor declares that it throws Exception itself.

在actionPerformed(ActionEvent e)中,您调用encrypt(),声明它将抛出异常。但是,actionPerformed既没有捕获此异常(使用try / catch围绕对encrypt()的调用)也没有声明它会抛出异常本身。

Your encrypt method, however, does not truly throw Exception. It swallows all Exceptions without even as much as logging a complaint. (Bad practice and bad style!)

但是,您的加密方法并不会真正抛出异常。它吞没了所有异常,甚至没有记录投诉。 (糟糕的做法和糟糕的风格!)

Also, your encrypt method does the following:

此外,您的加密方法执行以下操作:

public static byte[] encrypt(String toEncrypt) throws Exception {
  try{
    ....
    return encrypted; // HERE YOU CORRECTLY RETURN A VALUE
  } catch(Exception e) {
  }
  // YOU DO NOT RETURN ANYTHING HERE
}

That is, if you do catch any Exception, you discard it silently and then fall off the bottom of your encrypt method without actually returning anything. This won't compile (as you see), because a method that is declared to return a value must either return a value or throw an Exception for every single possible code path.

也就是说,如果你捕获任何异常,你会以静默方式丢弃它,然后从加密方法的底部掉下来而不实际返回任何内容。这将无法编译(如您所见),因为声明为返回值的方法必须返回值或为每个可能的代码路径抛出异常。

#1


27  

All your problems derive from this

你所有的问题都源于此

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

Which are enclosed in a try, catch block, the problem is that in case the program found an exception you are not returning anything. Put it like this (modify it as your program logic stands):

其中包含在try,catch块中,问题是如果程序发现异常,则不返回任何内容。像这样(将其修改为程序逻辑):

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

For the second one you must catch the Exception from the encrypt method call, like this (also modify it as your program logic stands):

对于第二个,您必须从加密方法调用中捕获异常,如下所示(也可以将其修改为程序逻辑):

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

The lessons you must learn from this:

你必须从中吸取教训:

  • A method with a return-type must always return an object of that type, I mean in all possible scenarios
  • 具有返回类型的方法必须始终返回该类型的对象,我的意思是在所有可能的场景中

  • All checked exceptions must always be handled
  • 必须始终处理所有已检查的异常

#2


5  

The problem is in this method:

问题出在这个方法中:

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

This is the method signature which pretty much says:

这是方法签名,几乎说:

  • what the method name is: encrypt
  • 方法名称是什么:加密

  • what parameter it receives: a String named toEncrypt
  • 它接收的参数是什么:名为toEncrypt的String

  • its access modifier: public static
  • 其访问修饰符:public static

  • and if it may or not throw an exception when invoked.
  • 如果在调用时可能抛出异常。

In this case the method signature says that when invoked this method "could" potentially throw an exception of type "Exception".

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

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

So the compilers is saying: Either you surround that with a try/catch construct or you declare the method ( where is being used ) to throw "Exception" it self.

因此编译器会说:要么用try / catch构造包围它,要么声明方法(正在使用的地方)自己抛出“Exception”。

The real problem is the "encrypt" method definition. No method should ever return "Exception", because it is too generic and may hide some other kinds of exception better is to have an specific exception.

真正的问题是“加密”方法定义。没有方法应该返回“异常”,因为它太通用了,可能隐藏其他类型的异常更好的是有一个特定的异常。

Try this:

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.
  }

Basically in this particular case you should make sure the cryptography package is available in the system.

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

Java needs an extension for the cryptography package, so, the exceptions are declared as "checked" exceptions. For you to handle when they are not present.

Java需要加密包的扩展,因此,异常被声明为“已检查”的异常。当你不在场时你可以处理。

In this small program you cannot do anything if the cryptography package is not available, so you check that at "development" time. If those exceptions are thrown when your program is running is because you did something wrong in "development" thus a RuntimeException subclass is more appropriate.

在这个小程序中,如果加密包不可用,则无法执行任何操作,因此请在“开发”时检查该程序。如果在程序运行时抛出这些异常是因为你在“开发”中做错了,那么RuntimeException子类更合适。

The last line don't need a return statement anymore, in the first version you were catching the exception and doing nothing with it, that's wrong.

最后一行不再需要return语句,在第一个版本中你捕获异常而对它一无所知,这是错误的。

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???

If the code is to fail, it is better to Fail fast

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

Here are some related answers:

以下是一些相关的答案:

#3


3  

The first error

第一个错误

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

java.lang.Exception的;必须被捕获或声明被抛出byte [] encrypted = encrypt(concatURL);

means that your encrypt method throws an exception that is not being handled or declared by the actionPerformed method where you are calling it. Read all about it at the Java Exceptions Tutorial.

表示您的encrypt方法抛出一个异常,该异常未被您调用它的actionPerformed方法处理或声明。阅读Java Exceptions Tutorial中的所有相关内容。

You have a couple of choices that you can pick from to get the code to compile.

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

  • You can remove throws Exception from your encrypt method and actually handle the exception inside encrypt.
  • 您可以从加密方法中删除throws Exception,并实际处理加密内部的异常。

  • You can remove the try/catch block from encrypt and add throws Exception and the exception handling block to your actionPerformed method.
  • 您可以从encrypt中删除try / catch块,并向您的actionPerformed方法添加throws Exception和异常处理块。

It's generally better to handle an exception at the lowest level that you can, instead of passing it up to a higher level.

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

The second error just means that you need to add a return statement to whichever method contains line 109 (also encrypt, in this case). There is a return statement in the method, but if an exception is thrown it might not be reached, so you either need to return in the catch block, or remove the try/catch from encrypt, as I mentioned before.

第二个错误只是意味着您需要将return语句添加到包含第109行的任何方法(在这种情况下也加密)。方法中有一个return语句,但如果抛出异常,则可能无法访问,因此您需要返回catch块,或者从encrypt中删除try / catch,如前所述。

#4


1  

You'll need to decide how you'd like to handle exceptions thrown by the encrypt method.

您需要决定如何处理encrypt方法抛出的异常。

Currently, encrypt is declared with throws Exception - however, in the body of the method, exceptions are caught in a try/catch block. I recommend you either:

目前,使用throws Exception声明encrypt - 但是,在方法的主体中,异常会在try / catch块中捕获。我推荐你:

  • remove the throws Exception clause from encrypt and handle exceptions internally (consider writing a log message at the very least); or,
  • 从加密中删除throws Exception子句并在内部处理异常(考虑至少写一条日志消息);要么,

  • remove the try/catch block from the body of encrypt, and surround the call to encrypt with a try/catch instead (i.e. in actionPerformed).
  • 从加密体中删除try / catch块,并用try / catch代替加密调用(即在actionPerformed中)。

Regarding the compilation error you refer to: if an exception was thrown in the try block of encrypt, nothing gets returned after the catch block finishes. You could address this by initially declaring the return value as null:

关于编译错误,请参考:如果在加密的try块中抛出异常,则在catch块完成后不会返回任何内容。您可以通过最初将返回值声明为null来解决此问题:

public static byte[] encrypt(String toEncrypt) throws Exception{
  byte[] encrypted = null;
  try {
    // ...
    encrypted = ...
  }
  catch(Exception e){
    // ...
  }
  return encrypted;
}

However, if you can correct the bigger issue (the exception-handling strategy), this problem will take care of itself - particularly if you choose the second option I've suggested.

但是,如果您可以纠正更大的问题(异常处理策略),这个问题将自行处理 - 特别是如果您选择我建议的第二个选项。

#5


0  

In your 'encrypt' method, you should either get rid of the try/catch and instead add a try/catch around where you call encrypt (inside 'actionPerformed') or return null inside the catch within encrypt (that's the second error.

在你的'encrypt'方法中,你应该摆脱try / catch,而是在你调用encrypt(在'actionPerformed'内)的地方添加一个try / catch,或者在encrypt中的catch内返回null(这是第二个错误。

#6


0  

In actionPerformed(ActionEvent e) you call encrypt(), which is declared to throw Exception. However, actionPerformed neither catches this Exception (with try/catch around the call to encrypt()) nor declares that it throws Exception itself.

在actionPerformed(ActionEvent e)中,您调用encrypt(),声明它将抛出异常。但是,actionPerformed既没有捕获此异常(使用try / catch围绕对encrypt()的调用)也没有声明它会抛出异常本身。

Your encrypt method, however, does not truly throw Exception. It swallows all Exceptions without even as much as logging a complaint. (Bad practice and bad style!)

但是,您的加密方法并不会真正抛出异常。它吞没了所有异常,甚至没有记录投诉。 (糟糕的做法和糟糕的风格!)

Also, your encrypt method does the following:

此外,您的加密方法执行以下操作:

public static byte[] encrypt(String toEncrypt) throws Exception {
  try{
    ....
    return encrypted; // HERE YOU CORRECTLY RETURN A VALUE
  } catch(Exception e) {
  }
  // YOU DO NOT RETURN ANYTHING HERE
}

That is, if you do catch any Exception, you discard it silently and then fall off the bottom of your encrypt method without actually returning anything. This won't compile (as you see), because a method that is declared to return a value must either return a value or throw an Exception for every single possible code path.

也就是说,如果你捕获任何异常,你会以静默方式丢弃它,然后从加密方法的底部掉下来而不实际返回任何内容。这将无法编译(如您所见),因为声明为返回值的方法必须返回值或为每个可能的代码路径抛出异常。