我故意为特定场景抛出异常,但我会隐含地希望以字符串格式获取错误消息。我知道以下异常的一个重载是string message
,但是如何访问该字符串呢?
以下是相关摘录:
string errMsg;
private void Compress()
{
if (sourcePath.EndsWith(".zip"))
{
throw new FileLoadException
("File already compressed. Unzip the file and try again.");
errMsg = //I want the above string here
}
}
答案 0 :(得分:8)
你的意思是:?
try
{
throw new FileLoadException
("File already compressed. Unzip the file and try again.");
}
catch (Exception ex)
{
errMsg = ex.GetBaseException().Message;
}
答案 1 :(得分:2)
你无法访问字符串我会在那里解释一下:
string errMsg;
private void Compress()
{
if (sourcePath.EndsWith(".zip"))
{
throw new FileLoadException
("File already compressed. Unzip the file and try again.");
// The following line is unreachable as the throw ends the function and gets the exception to the calling function as there is no try catch block to catch the exception.
errMsg = //I want the above string here
}
}
可能是try/catch
要设置变量的方法中的异常:
private void Compress()
{
if (sourcePath.EndsWith(".zip"))
{
try
{
throw new FileLoadException
("File already compressed. Unzip the file and try again.");
}
catch (Exception e)
{
errMsg = e.Message;
}
}
}
或者在调用方法中捕获异常:
try
{
Compress();
}
catch (Exception e)
{
}
无论使用何种方法,e.Message都会以字符串的形式向您提供异常消息。
答案 2 :(得分:1)
没有必要尝试捕获异常并设置消息。除非你重新扔掉它
try
{
throw new FileLoadException("File already compressed. Unzip the file and try again.");
}
catch (Exception ex)
{
errMsg = ex.GetBaseException().Message;
throw;
}
我宁愿这样做
private void Compress()
{
if (sourcePath.EndsWith(".zip"))
{
errMsg = "File already compressed. Unzip the file and try again.";
return;
}
}
答案 3 :(得分:0)
不确定我是否100%理解,但如果您想要来自该异常的消息,您可以捕获它并检查Exception.Message
try
{
throw new FileLoadException("Custom error string");
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
答案 4 :(得分:0)
这里应该是一个解决方案:)
if (sourcePath.EndsWith(".zip"))
{
FileLoadException ex = new FileLoadException("File already compressed. Unzip the file and try again.");
errMsg = ex.ToString();
}
Console.WriteLine(errMsg);
要抛出你所做的异常,我会像这样做
static string sourcePath = "test.zip"; //hardcoded file
static string errMsg; //the error string
private static void Compress()
{
try
{
if (!sourcePath.EndsWith(".zip"))
{
Console.WriteLine("File doesn't end with zip so it can be compressed"); //if it does not end with zip its rdy for compressing and here you can indput your code to compress
}
else
{
throw new Exception(); //instead of using try catch you can also generate the code in here instead of throwing an exception.
//when throwing a new exception you make it stop the if setting and jump into the catch if you use break it wont enter the catch but instead it will just jump over it.
}
}
catch
{
//Here it will generate the custom exception you wanted and put it inside the errMsg
errMsg = new FileLoadException("File already compressed. Unzip the file and try again.").ToString();
Console.WriteLine(errMsg);
}
ofc这是在控制台中制作的,这就是为什么我使用console.writeline你可以改变那些