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

后端 未结 6 720
粉色の甜心
粉色の甜心 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:16

    The first error

    java.lang.Exception; must be caught or declared to be thrown 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.

    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.
    • You can remove the try/catch block from encrypt and add throws Exception and the exception handling block to your actionPerformed method.

    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.

提交回复
热议问题