Home >Java >javaTutorial >Why Must Java Exceptions Be Caught or Declared?
Why does Java require exceptions to be caught or declared to be thrown?
In Java, a method can throw an exception if an error occurs during its execution. If the method does not handle the exception explicitly, it must declare the exception in its method signature. This forces the caller of the method to handle the exception or to declare the exception in its own method signature.
Why do you get the exception "java.lang.Exception; must be caught or declared to be thrown"?
This exception occurs when a method calls another method that throws a checked exception, but the calling method does not handle the exception or declare it in its method signature.
In your code, the encrypt method throws a javax.crypto.IllegalBlockSizeException checked exception, but the actionPerformed method does not handle or declare this exception.
How to solve the problem
To solve this problem, you can either handle the exception in the actionPerformed method or declare the exception in the method signature.
Handling the exception:
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 the exception } }
Declaring the exception:
public void actionPerformed(ActionEvent e) throws Exception { byte[] encrypted = encrypt(concatURL); String encryptedString = bytesToHex(encrypted); content.removeAll(); content.add(new JLabel("Concatenated User Input -->" + concatURL)); content.add(encryptedTextField); setContentPane(content); }
Missing return statement error:
This error occurs because the encrypt method does not have a return statement in the catch block. This means that the method does not return anything in case of an exception, which is not allowed.
To solve this problem, you can add a return statement to the catch block, as shown below:
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 } }
The above is the detailed content of Why Must Java Exceptions Be Caught or Declared?. For more information, please follow other related articles on the PHP Chinese website!