缩短错误

问题描述 投票:-4回答:3

我在c#中创建了一个程序(我没有在这里放置代码,因为有很多类),并且我使用Exceptions来抛出错误,当出现错误时,这就是控制台中出现的内容:

System.Exception:Student whit id:1已经存在! at StudentManagment.Service.AbstractService`4.Add(E entity)位于C:\ Users \ Robbi \ source \ repos \ StudentManagment \ StudentManagment \ Service \ AbstractService.cs:第34行,地址为StudentManagment.Domain.Program.Main(String [] args)在C:\ Users \ Robbi \ source \ repos \ StudentManagment \ StudentManagment \ Program.cs:第23行

我的问题是,我怎样才能在控制台中使其显示为正好

身份:1的学生已经存在!

c# exception
3个回答
1
投票

将异常捕获到变量中并仅输出exception.Message。您正在查看堆栈跟踪 - 即在错误点执行的所有方法。 StackTraces对于调试目的很有用,但对于向用户显示信息却不是很好。

try 
{
   //do error here
}
catch(Exception e)
{
   Console.WriteLine(e.Message);
}

1
投票

这是一个非常初学的问题

虽然你没有显示任何代码,但仍有一些半假代码来回答这个问题

try
{
  do_it();
}
catch (Exception myEx) // you can do different things with different exception types
{
  Console.WriteLine("Error: "+myEx.Message);
}

1
投票

你必须使用

ex.Message

其中ex是你的除外,类似于

try 
{ 
    ...
} 
catch (Exception ex) 
{ 
    Console.Write(ex.Message); 
}

当然,编辑此最小代码段代码以满足您的需求

© www.soinside.com 2019 - 2024. All rights reserved.