未报告的exceptionjava.lang.exception
未报告的exceptionjava.lang.exception:必须被捕获或声明为throw。 为什么会出现这个问题? 是否有一些简单的方法可以帮助解决这个问题?
我在我的java中应用此代码..
public byte[] encrypt(String message) throws Exception { MessageDigest md = MessageDigest.getInstance("md5"); byte[] digestOfPassword = md.digest("ABCDEABCDE" .getBytes("utf-8")); byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); for (int j = 0, k = 16; j < 8;) { keyBytes[k++] = keyBytes[j++]; } SecretKey key = new SecretKeySpec(keyBytes, "DESede"); IvParameterSpec iv = new IvParameterSpec(new byte[8]); Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key, iv); byte[] plainTextBytes = message.getBytes("utf-8"); byte[] cipherText = cipher.doFinal(plainTextBytes); // String encodedCipherText = new sun.misc.BASE64Encoder() // .encode(cipherText); return cipherText; } public String decrypt(byte[] message) throws Exception { MessageDigest md = MessageDigest.getInstance("md5"); byte[] digestOfPassword = md.digest("ABCDEABCDE" .getBytes("utf-8")); byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); for (int j = 0, k = 16; j < 8;) { keyBytes[k++] = keyBytes[j++]; } SecretKey key = new SecretKeySpec(keyBytes, "DESede"); IvParameterSpec iv = new IvParameterSpec(new byte[8]); Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); decipher.init(Cipher.DECRYPT_MODE, key, iv); byte[] plainText = decipher.doFinal(message); return new String(plainText, "UTF-8"); }
错误如下所示
byte[] pass = encrypt(password); String pw = new String(pass);
任何想法? 我用java netbeans来做我的项目..
您的encrypt()
方法抛出Exception
。 这意味着在您调用此方法的地方,您应该明确地抛出此Exception
或使用try-catch
块处理它。
在您的情况下,对于此特定代码:
byte[] pass = encrypt(password); String pw = new String(pass);
你应该把它包括在:
try{ byte[] pass = encrypt(password); String pw = new String(pass); }catch(Exception exe){ //Your error handling code }
或者使用throws Exception
声明包含此代码的方法。
-
如果您不熟悉exception处理,请考虑阅读: 课程:Java教程中的exception
-
另外,这是关于“exception传播指南(Java)”的另一篇有趣的读物
1.有两种方法可以处理exception。
- Either `declare` it - or `Handle` it.
2.上面的encrypt()
方法抛出exception
因此,要么在您调用它的方法声明中声明它。
例如:
public void MyCallingMethod() throws Exception{ byte[] pass = encrypt(password); String pw = new String(pass); }
或者使用 try/catch
块 处理它 , finally
是可选的
try{ byte[] pass = encrypt(password); String pw = new String(pass); }catch(Exception ex){ }