Why do I get “Exception; must be caught or declared to be thrown” when I try to compile my Java code?

后端 未结 6 753
粉色の甜心
粉色の甜心 2020-11-22 08:46

Consider:

import java.awt.*;

import javax.swing.*;
import java.awt.event.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
impor         


        
6条回答
  •  醉话见心
    2020-11-22 09:18

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

    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:

    • remove the throws Exception clause from encrypt and handle exceptions internally (consider writing a log message at the very least); or,
    • 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).

    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:

    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.

提交回复
热议问题