为什么我得到“异常;必须被抓住或宣布被抛出“当我尝试编译我的Java代码? [英] Why do I get "Exception; must be caught or declared to be thrown" when I try to compile my Java code?

查看:152
本文介绍了为什么我得到“异常;必须被抓住或宣布被抛出“当我尝试编译我的Java代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

任何人都可以帮助我解决这些问题问题?

Can anyone help me with solving these problems?

推荐答案

所有的问题源于这个

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

其中包含在try,catch块中,问题是如果程序发现异常你没有返回任何东西。把它像这样(修改它作为你的程序逻辑立场):

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):

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

这篇关于为什么我得到“异常;必须被抓住或宣布被抛出“当我尝试编译我的Java代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆