就我的努力而言,我无法解决我的Decrypt方法抛出的异常。在将数据转换为缓冲区字节数组的行上,抛出了ArgumentNullException。首先我添加了一个:
if (String.IsNullOrEmpty(data))
{
throw new ArgumentNullException ("Null data");
}
同样对于密码,我做了相同的代码。然后,在if语句中弹出相同的异常后,我将其更改为下面的try-catch语句。现在异常不会在try-catch行上弹出,而是在Decrypt中的缓冲区转换行上弹出。我不太确定程序想要什么,因为我认为try-catch可以解决这个问题,但我对C#也很陌生,所以我可能会遗漏一些明显的东西。
public static string Encrypt (string data, string password)
{
if (String.IsNullOrEmpty(data as string))
{
throw new ArgumentException("Null data.");
}
if (String.IsNullOrEmpty(password as string))
{
throw new ArgumentException("Null password.");
}
using (SymmetricAlgorithm alg = GetAlgorithm(password))
using (MemoryStream ms = new MemoryStream())
using (CryptoStream cs = new CryptoStream (ms, alg.CreateEncryptor(), CryptoStreamMode.Write))
{
byte[] buffer = Encoding.UTF8.GetBytes(data);
cs.Write(buffer, 0, buffer.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
}
public static string Decrypt (string data, string password)
{
try
{
String.IsNullOrEmpty(data);
}
catch
{
throw new ArgumentException("Null data.");
}
try
{
String.IsNullOrEmpty(password);
}
catch
{
throw new ArgumentException("Null password.");
}
using (SymmetricAlgorithm alg = GetAlgorithm(password))
using (MemoryStream ms = new MemoryStream())
using (CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write))
{
byte[] buffer = Convert.FromBase64String(data);//This is where the exception occurs
cs.Write(buffer, 0, buffer.Length);
cs.FlushFinalBlock();
buffer = ms.ToArray();
return Convert.ToBase64String(buffer);
}
}
答案 0 :(得分:2)
这段代码绝对没有:
try
{
String.IsNullOrEmpty(data);
}
catch
{
throw new ArgumentException("Null data.");
}
这是因为String.IsNullOrEmpty()
不会抛出异常。它返回bool
。但你没有做任何返回值的事情。返回的任何内容都会在语句结束时被丢弃。
因此,如果data
为null
,那么当您稍后尝试在方法中使用它时,您将获得异常:
byte[] buffer = Convert.FromBase64String(data);
您的其他方法已正确检查null
值。那么为什么不使用相同的方法呢?
if (String.IsNullOrEmpty(data))
throw new ArgumentException("Null data.");
总的来说,不要将try/catch
块用于应用程序逻辑。这些是用于捕获和处理异常。如果您只需要检查条件是否为真,请使用if
语句。此外,忽略他们捕获的实际异常的catch
块是着名的坏主意。它抛弃了有意义的异常信息,使错误诊断更加困难。