想了解Mocha/Chaiexpect.to.throw没有捕捉到抛出的错误的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于未捕获异常该怎样处理的相关问题,此外,我们还将为您介绍关于.net
想了解Mocha / Chai expect.to.throw 没有捕捉到抛出的错误的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于未捕获异常该怎样处理的相关问题,此外,我们还将为您介绍关于.net – 无法加载Exchange powershell管理单元:“Microsoft.Exchange.Data.Directory.Globals”的类型初始化程序抛出异常、Airbnb Challenge and Expectations、c# – 顶级异常没有捕捉到任何东西、C#中try catch中throw ex和throw方式抛出异常有何不同_异常捕获堆栈丢失问题 C#中try catch中throw ex和throw方式抛出异常有何不同的新知识。
本文目录一览:- Mocha / Chai expect.to.throw 没有捕捉到抛出的错误(未捕获异常该怎样处理)
- .net – 无法加载Exchange powershell管理单元:“Microsoft.Exchange.Data.Directory.Globals”的类型初始化程序抛出异常
- Airbnb Challenge and Expectations
- c# – 顶级异常没有捕捉到任何东西
- C#中try catch中throw ex和throw方式抛出异常有何不同_异常捕获堆栈丢失问题 C#中try catch中throw ex和throw方式抛出异常有何不同
Mocha / Chai expect.to.throw 没有捕捉到抛出的错误(未捕获异常该怎样处理)
我在让 Chai’sexpect.to.throw
在我的 node.js
应用程序的测试中工作时遇到问题。测试在抛出的错误上一直失败,但是如果我将测试用例包装在 try 中并捕获并断言捕获的错误,它就可以工作。
expect.to.throw
不像我认为的那样工作还是什么?
it(''should throw an error if you try to get an undefined property'', function (done) { var params = { a: ''test'', b: ''test'', c: ''test'' }; var model = new TestModel(MOCK_REQUEST, params); // neither of these work expect(model.get(''z'')).to.throw(''Property does not exist in model schema.''); expect(model.get(''z'')).to.throw(new Error(''Property does not exist in model schema.'')); // this works try { model.get(''z''); } catch(err) { expect(err).to.eql(new Error(''Property does not exist in model schema.'')); } done();});
失败:
19 passing (25ms) 1 failing 1) Model Base should throw an error if you try to get an undefined property: Error: Property does not exist in model schema.
答案1
小编典典您必须将函数传递给expect
. 像这样:
expect(model.get.bind(model, ''z'')).to.throw(''Property does not exist in model schema.'');expect(model.get.bind(model, ''z'')).to.throw(new Error(''Property does not exist in model schema.''));
你这样做的方式是传递给调用expect
的
结果model.get(''z'')
。但是要测试是否有东西被抛出,你必须将一个函数传递给expect
,它expect
会调用自己。上面使用的bind
方法创建了一个新函数,调用该函数时将调用设置为的值model.get
和设置为的第一个参数。this``model``''z''
bind
可以在这里找到一个很好的解释。
.net – 无法加载Exchange powershell管理单元:“Microsoft.Exchange.Data.Directory.Globals”的类型初始化程序抛出异常
Dim runspaceConfig = RunspaceConfiguration.Create() Dim snapInException As PSSnapInException = nothing runspaceConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010",snapInException) Dim runspace = RunspaceFactory.CreateRunspace(runspaceConfig) runspace.open()
自从安装Visual Studio 2012以来,在执行将管理单元添加到runspace配置中的行时,我开始收到以下错误.
System.Management.Automation.Runspaces.PSSnapInException occurred HResult=-2146233087 Message=Cannot load Windows PowerShell snap-in Microsoft.Exchange.Management.PowerShell.E2010 because of the following error: The type initializer for 'Microsoft.Exchange.Data.Directory.Globals' threw an exception. Source=System.Management.Automation WasThrownFromThrowStatement=False StackTrace: at System.Management.Automation.Runspaces.RunspaceConfigForSingleShell.LoadCustomPSSnapIn(PSSnapInInfo mshsnapinInfo) at System.Management.Automation.Runspaces.RunspaceConfigForSingleShell.LoadPSSnapIn(PSSnapInInfo mshsnapinInfo) at System.Management.Automation.Runspaces.RunspaceConfigForSingleShell.LoadPSSnapIn(PSSnapInInfo mshsnapinInfo,PSSnapInException& warning) at System.Management.Automation.Runspaces.RunspaceConfigForSingleShell.DoAddPSSnapIn(String name,PSSnapInException& warning) at System.Management.Automation.Runspaces.RunspaceConfiguration.AddPSSnapIn(String name,PSSnapInException& warning)
我已经能够确认nlog是不知何故导致这个问题.在创建powershell runspace之前创建一个nlog记录器的组合会导致错误.
如果我从我的应用程序配置中删除nlog配置部分,只需创建一个空的nlog记录器,那么加载中没有错误.另外,如果我在应用程序配置中留下了nlog配置,但是不创建一个nlog记录器,那么管理单元也被成功加载.
>我已经尝试在x64和x86中构建项目.
>我已经重新安装了交换管理工具.
>我已经尝试在交换环境中的另一台机器上进行测试.
如果有人可以提供任何可能帮助我解决这个问题的建议,我将会很有意思.
谢谢
有关更新的更多信息,请参阅以下文章.
http://www.devproconnections.com/article/net-framework/net-framework-45-versioning-faces-problems-141160
Airbnb Challenge and Expectations
Challenge and Expectations
Isn’t data just more fun when you can interact and play with it? Well, that’s exactly how
we challenge our data analysts at Capital One. We need to find great people to join our
team as we develop software data products across our three key areas of data work:
Builder Mindset: Leverages creative and adaptive problem solving to selecting
the right tool for the job; seeks automated and efficient solutions to manual or
repetitive processes.
Data Management: Strategically leads efforts to systematically evaluate, and
document; monitors our data in a sustained and organizationally recognized way
Business Intent: Translates business needs into actionable solutions or data
products; effectively communicate results to stakeholders and technical partners.
This challenge is your next step in showing Capital One what you can do. After
receiving data instructions you’re putting hands-to-keyboard and have 1 week to submit
a working data product, per the submission instructions, including:
Working code with documentation
Documentation of metadata and data quality
Visualizations of key insights
Ready to show off your data chops? Let’s go!
Problem Statement and Instructions
Problem Statement
You are consulting for a real estate company that has a niche in purchasing properties to
data analysts 作业代写、代做 Python,Java 程序语言作业、Java/Python 课程设计作业代写
rent out short-term as part of their business model specifically within New York City. The
real estate company has already concluded that two bedroom properties are the most
profitable; however, they do not know which zip codes are the best to invest in.
The real estate company has engaged your firm to build out a data product and provide
your conclusions to help them understand which zip codes would generate the most
profit on short term rentals within New York City.
. You will be looking at publicly available data from Zillow and AirBnB:
Cost data: Zillow provides us an estimate of value for two-bedroom properties
Revenue data: AirBnB is the medium through which the investor plans to lease
out their investment property. Fortunately for you, we are able to see how
much properties in certain neighborhoods rent out for in New York City
You can assume an occupancy rate of 75% or you can come up with your own
model to calculate occupancy; just let us know how you came to that
calculation
Capital One Confidential
After meeting with the strategy team, you’ve got an idea of where to start, key concerns,
and how you can help this real estate company with the market data while keeping the
following assumptions in mind:
The investor will pay for the property in cash (i.e. no mortgage/interest rate will
need to be accounted for).
The time value of money discount rate is 0% (i.e. $1 today is worth the same
100 years from now).
All properties and all square feet within each locale can be assumed to be
homogeneous (i.e. a 1000 square foot property in a locale such as Bronx or
Manhattan generates twice the revenue and costs twice as much as any other
500 square foot property within that same locale.)
Capital One Confidential
Instructions
As you start the challenge, realize that this is real-world, imperfect data. We recommend
planning about 4 hours to complete the Data Challenge, but it’s not timed, and you are
judged on the quality of the work submitted. If you find yourself uncertain of what the
“right” answer is, use your best judgment, make an assumption (document the
assumption), and keep going.
Overall, we first ask you to show your data skills in three areas at a basic level, and then,
in the last step, tell us what you would do next to provide a better conclusion.
1. Quality Check – bad data is worse than no data at all
a. Understand the data while keeping your final output in mind
b. Highlight two to three data quality insights based on your analysis of the
data
c. Create metadata for any derived fields or metrics used to complete your
analysis
2. Data munging – get the data
a. The datasets do have different units of time – in order to complete the
analysis, you will need to determine a common unit of time
b. Write a function that can link the data together in a scalable way when
new data is available or for when we are ready to approach a new market
3. Craft a visual data narrative – Charts and plots must be generated from your
code; not from produced in external standalone software like Excel
a. Visualize metrics for profitability on short term rentals by zip code
b. Summarize your key insights and conclusions based on the data and your
analysis
4. What’s Next – We recognize that 4 hours isn’t a lot of time… and you’ve
probably come up with a number of great ideas from an analytical or visualization
perspective that you don’t have time to do. Tell us (but don’t do any work) what
you would/could do next to inform a better decision or deliver a better product to
the real estate company.
Data and Tools
Solutions that require purchase of a software license or purchased access to data will
not be accepted regardless of whether or not Capital One uses said software or data.
Abide by all applicable laws and regulations regarding the use of software or external
data sources. If you have questions about a particular software package, please contact
your recruiter immediately.
Data
Downloading the data is a simple two-step process: Please use the same web browser for
both links.
1. Please access the Capital One Data Challenge GitHub account via
https://github.com/login using the Username and Password provided in the email
from your recruiter.
2. Once logged in GitHub, please copy and paste the following link into your web
browser and press enter to download the ZIP file.
a. https://github.com/c1-data-analytics/airbnb-zillow-datachallenge/archive/master.zip
Capital One Confidential
The ZIP file will contain the following list of data and metadata files necessary for you to work
through this Data Challenge. Please do not change the username or password while accessing
this account.
Data
Resource You should see
This document AirBnB_Zillow – Data Challenge.docx
Technical Considerations Data_Challenge_Technical_Considerations.html
Main input data sets AirBnb
Link provided in “AirBnB Dataset Link.txt” file.
Copy and paste the link and the download will
begin
Zillow
Zip_Zhvi_2bedroom.csv.zip
Metadata AirBnB_Zillow – Metadata.docx
Tools
Here are some example platforms you should feel free to use. By no means are you
limited to this list, and our solution review team will be able to evaluate solutions in most
languages. If you really do have a question about the platform you would like to use to
solve the problem, contact your recruiter with the exact setup you’d like to use (including
OS and specific versions when applicable), your backup choice, and they can seek
verification for the platform
Platform example Notable packages
Anaconda Python Distribution notebook, pandas, matplotlib, bokeh
R R, Shiny, plyr, ggplot
Javascript D3, nvd3, node.js, Tableau
Java virtual machine Groovy, Scala
Other software packages with which you are familiar
How to submit
Congratulations on completing the Data Challenge! Please see the
following instructions for how to submit your work.
Submission is easy – just email to dataanalysisrecruitingmailbox@capitalone.com a
single ZIP file (< 10 MB) containing:
1. Working source code file with documentation
Code
Capital One Confidential
Source documentation (e.g., a README file)
Any generated graphics files
If you added data: if you added more than a couple of MB of data, provide
a program or script, with documentation, to download the data set
2. Documentation including metadata for any data created and your data quality
insights
3. Visualizations and key insights from those visualizations
Please do not post your code or documents to any public repositories.
Acknowledgements
The data for this challenge were sourced from:
Zillow Group, Inc. (2016)
Airbnb
data analysts 作业代写、代做 Python,Java 程序语言作业、Java/Python 课程设计作业代写
Challenge and Expectations
Isn’t data just more fun when you can interact and play with it? Well, that’s exactly how
we challenge our data analysts at Capital One. We need to find great people to join our
team as we develop software data products across our three key areas of data work:
Builder Mindset: Leverages creative and adaptive problem solving to selecting
the right tool for the job; seeks automated and efficient solutions to manual or
repetitive processes.
Data Management: Strategically leads efforts to systematically evaluate, and
document; monitors our data in a sustained and organizationally recognized way
Business Intent: Translates business needs into actionable solutions or data
products; effectively communicate results to stakeholders and technical partners.
This challenge is your next step in showing Capital One what you can do. After
receiving data instructions you’re putting hands-to-keyboard and have 1 week to submit
a working data product, per the submission instructions, including:
Working code with documentation
Documentation of metadata and data quality
Visualizations of key insights
Ready to show off your data chops? Let’s go!
Problem Statement and Instructions
Problem Statement
You are consulting for a real estate company that has a niche in purchasing properties to
rent out short-term as part of their business model specifically within New York City. The
real estate company has already concluded that two bedroom properties are the most
profitable; however, they do not know which zip codes are the best to invest in.
The real estate company has engaged your firm to build out a data product and provide
your conclusions to help them understand which zip codes would generate the most
profit on short term rentals within New York City.
. You will be looking at publicly available data from Zillow and AirBnB:
Cost data: Zillow provides us an estimate of value for two-bedroom properties
Revenue data: AirBnB is the medium through which the investor plans to lease
out their investment property. Fortunately for you, we are able to see how
much properties in certain neighborhoods rent out for in New York City
You can assume an occupancy rate of 75% or you can come up with your own
model to calculate occupancy; just let us know how you came to that
calculation
Capital One Confidential
After meeting with the strategy team, you’ve got an idea of where to start, key concerns,
and how you can help this real estate company with the market data while keeping the
following assumptions in mind:
The investor will pay for the property in cash (i.e. no mortgage/interest rate will
need to be accounted for).
The time value of money discount rate is 0% (i.e. $1 today is worth the same
100 years from now).
All properties and all square feet within each locale can be assumed to be
homogeneous (i.e. a 1000 square foot property in a locale such as Bronx or
Manhattan generates twice the revenue and costs twice as much as any other
500 square foot property within that same locale.)
Capital One Confidential
Instructions
As you start the challenge, realize that this is real-world, imperfect data. We recommend
planning about 4 hours to complete the Data Challenge, but it’s not timed, and you are
judged on the quality of the work submitted. If you find yourself uncertain of what the
“right” answer is, use your best judgment, make an assumption (document the
assumption), and keep going.
Overall, we first ask you to show your data skills in three areas at a basic level, and then,
in the last step, tell us what you would do next to provide a better conclusion.
1. Quality Check – bad data is worse than no data at all
a. Understand the data while keeping your final output in mind
b. Highlight two to three data quality insights based on your analysis of the
data
c. Create metadata for any derived fields or metrics used to complete your
analysis
2. Data munging – get the data
a. The datasets do have different units of time – in order to complete the
analysis, you will need to determine a common unit of time
b. Write a function that can link the data together in a scalable way when
new data is available or for when we are ready to approach a new market
3. Craft a visual data narrative – Charts and plots must be generated from your
code; not from produced in external standalone software like Excel
a. Visualize metrics for profitability on short term rentals by zip code
b. Summarize your key insights and conclusions based on the data and your
analysis
4. What’s Next – We recognize that 4 hours isn’t a lot of time… and you’ve
probably come up with a number of great ideas from an analytical or visualization
perspective that you don’t have time to do. Tell us (but don’t do any work) what
you would/could do next to inform a better decision or deliver a better product to
the real estate company.
Data and Tools
Solutions that require purchase of a software license or purchased access to data will
not be accepted regardless of whether or not Capital One uses said software or data.
Abide by all applicable laws and regulations regarding the use of software or external
data sources. If you have questions about a particular software package, please contact
your recruiter immediately.
Data
Downloading the data is a simple two-step process: Please use the same web browser for
both links.
1. Please access the Capital One Data Challenge GitHub account via
https://github.com/login using the Username and Password provided in the email
from your recruiter.
2. Once logged in GitHub, please copy and paste the following link into your web
browser and press enter to download the ZIP file.
a. https://github.com/c1-data-analytics/airbnb-zillow-datachallenge/archive/master.zip
Capital One Confidential
The ZIP file will contain the following list of data and metadata files necessary for you to work
through this Data Challenge. Please do not change the username or password while accessing
this account.
Data
Resource You should see
This document AirBnB_Zillow – Data Challenge.docx
Technical Considerations Data_Challenge_Technical_Considerations.html
Main input data sets AirBnb
Link provided in “AirBnB Dataset Link.txt” file.
Copy and paste the link and the download will
begin
Zillow
Zip_Zhvi_2bedroom.csv.zip
Metadata AirBnB_Zillow – Metadata.docx
Tools
Here are some example platforms you should feel free to use. By no means are you
limited to this list, and our solution review team will be able to evaluate solutions in most
languages. If you really do have a question about the platform you would like to use to
solve the problem, contact your recruiter with the exact setup you’d like to use (including
OS and specific versions when applicable), your backup choice, and they can seek
verification for the platform
Platform example Notable packages
Anaconda Python Distribution notebook, pandas, matplotlib, bokeh
R R, Shiny, plyr, ggplot
Javascript D3, nvd3, node.js, Tableau
Java virtual machine Groovy, Scala
Other software packages with which you are familiar
How to submit
Congratulations on completing the Data Challenge! Please see the
following instructions for how to submit your work.
Submission is easy – just email to dataanalysisrecruitingmailbox@capitalone.com a
single ZIP file (< 10 MB) containing:
1. Working source code file with documentation
Code
Capital One Confidential
Source documentation (e.g., a README file)
Any generated graphics files
If you added data: if you added more than a couple of MB of data, provide
a program or script, with documentation, to download the data set
2. Documentation including metadata for any data created and your data quality
insights
3. Visualizations and key insights from those visualizations
Please do not post your code or documents to any public repositories.
Acknowledgements
The data for this challenge were sourced from:
Zillow Group, Inc. (2016)
Airbnb
http://www.6daixie.com/contents/9/3673.html
c# – 顶级异常没有捕捉到任何东西
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using System.Threading; using System.Runtime.InteropServices; namespace EyeScanner { static class Program { [FlagsAttribute] public enum EXECUTION_STATE : uint { ES_AWAYMODE_required = 0x00000040,ES_CONTINUOUS = 0x80000000,ES_disPLAY_required = 0x00000002,ES_SYstem_required = 0x00000001 // Legacy flag,should not be used. // ES_USER_PRESENT = 0x00000004 } [DllImport("kernel32.dll",CharSet = CharSet.Auto,SetLastError = true)] static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags); /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS | EXECUTION_STATE.ES_AWAYMODE_required | EXECUTION_STATE.ES_SYstem_required); bool isNew; Mutex m = new Mutex(false,"EyeScannerByOphthaMetrics",out isNew); try { if (isNew) Application.Run(new CheckSystemForm()); else { MessageBox.Show("An other instance of EyeScanner is running"); } } catch (Exception ex) { MessageBox.Show(ex.StackTrace); } } } }
现在我会期望最后一个catch()捕获任何未处理的异常,但是我有一个情况(100%可重复)创建一个NullReferenceException(将硬件连接到系统关闭),但我不能断点因为它发生在一个随机的点,我无法捕获它,我不能得到一个调用栈(当我尝试调试它,Visual Studio说发生了一个异常,没有CallStack,没有拆解可用).我在调试菜单中激活了NullReferenceException,但没有抓住它.
我该怎么处理?我有100%的异常,但我无法调试它,以找出为什么会发生.
编辑:
EventLog:
Anwendung: EyeScanner.exe Frameworkversion: v4.0.30319 Beschreibung: Der Prozess wurde aufgrund einer unbehandelten Ausnahme beendet. Ausnahmeinformationen: System.ObjectdisposedException Stapel: bei System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean ByRef) bei System.StubHelpers.StubHelpers.SafeHandleAddRef(System.Runtime.InteropServices.SafeHandle,Boolean ByRef) bei Microsoft.Win32.UnsafeNativeMethods.GetoverlappedResult(Microsoft.Win32.SafeHandles.SafeFileHandle,System.Threading.NativeOverlapped*,Int32 ByRef,Boolean) bei System.IO.Ports.SerialStream+EventLoopRunner.WaitForCommEvent() bei System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext,System.Threading.ContextCallback,System.Object,Boolean) bei System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext,System.Object) bei System.Threading.ThreadHelper.ThreadStart()
我绝对不知道在哪里寻找这个错误…
EDIT2:
我现在使用了SafeSerialStream,并且发生错误:
protected override void dispose(bool disposing) { if (disposing && (base.Container != null)) { base.Container.dispose(); } try { if (theBaseStream.CanRead) { theBaseStream.Close(); GC.ReRegisterForFinalize(theBaseStream); } } catch { // ignore exception - bug with USB - serial adapters. } base.dispose(disposing); }
在尝试执行BaseStream.Close()之后,代码正好崩溃,即使它在try {] catch {}块中.我该怎么办?
编辑3:
控制台输出崩溃:
A first chance exception of type 'System.IO.IOException' occurred in System.dll A first chance exception of type 'System.IO.IOException' occurred in System.dll A first chance exception of type 'system.invalidOperationException' occurred in System.dll 'EyeScanner.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Transactions.resources\v4.0_4.0.0.0_de_b77a5c561934e089\System.Transactions.resources.dll' System.Transactions Critical: 0 : <TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Critical"><TraceIdentifier>http://msdn.microsoft.com/TraceCodes/System/ActivityTracing/2004/07/Reliability/Exception/Unhandled</TraceIdentifier><Description>Unbehandelte Ausnahme</Description><AppDomain>EyeScanner.vshost.exe</AppDomain><Exception><ExceptionType>System.NullReferenceException,mscorlib,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089</ExceptionType><Message>Der Objektverweis wurde nicht auf eine Objektinstanz festgelegt.</Message><StackTrace> bei System.StubHelpers.StubHelpers.CheckCollectedDelegateMDA(IntPtr pEntryThunk)</StackTrace><ExceptionString>System.NullReferenceException: Der Objektverweis wurde nicht auf eine Objektinstanz festgelegt. bei System.StubHelpers.StubHelpers.CheckCollectedDelegateMDA(IntPtr pEntryThunk)</ExceptionString></Exception></TraceRecord> System.Transactions Critical: 0 : <TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Critical"><TraceIdentifier>http://msdn.microsoft.com/TraceCodes/System/ActivityTracing/2004/07/Reliability/Exception/Unhandled</TraceIdentifier><Description>Unbehandelte Ausnahme</Description><AppDomain>EyeScanner.vshost.exe</AppDomain><Exception><ExceptionType>System.NullReferenceException,PublicKeyToken=b77a5c561934e089</ExceptionType><Message>Der Objektverweis wurde nicht auf eine Objektinstanz festgelegt.</Message><StackTrace> bei System.StubHelpers.StubHelpers.CheckCollectedDelegateMDA(IntPtr pEntryThunk)</StackTrace><ExceptionString>System.NullReferenceException: Der Objektverweis wurde nicht auf eine Objektinstanz festgelegt. bei System.StubHelpers.StubHelpers.CheckCollectedDelegateMDA(IntPtr pEntryThunk)</ExceptionString></Exception></TraceRecord>
解决方法
C#中try catch中throw ex和throw方式抛出异常有何不同_异常捕获堆栈丢失问题 C#中try catch中throw ex和throw方式抛出异常有何不同
前言,最近遇到一个使用try-catch异常捕获后记录一下日志,然后再抛出该异常后,异常堆栈里无法显示准确的堆栈地址的问题? 其实以前也遇到过类似问题,没有重视,这次好好研究了下,并上度娘上找了找其他道友的文章一起看了,发现处理方式的不同的确会有影响!下面会详细介绍:
推荐使用:原始异常抛出写法(throw;),重点1!我们主要看初始的异常堆栈及错误信息,捕获异常的位置,一般会记录一些请求数据等。
我常用的使用try-catch捕获异常重新抛出的代码方式:
1 try{ 2 //代码块 3 }catch(Exception ex){ 4 日志处理 5 this.Logger.LogDebug(ex,$"记录异常"); 6 throw ex; 7 }
这用方式乍一看感觉没啥问题,我将异常做了日志处理后,直接又抛出去了,但是最终的异常堆栈里只显示了是在第6行抛出的异常,但是其实异常的位置应该是在第2行的代码块位置。我查了一位道友的文章发现,这种写法是有问题的,会导致初始的堆栈丢失!
划重点1-原始异常抛出: 将第5行的异常捕获改为:使用throw;接力抛出,而不是使用throw ex; 最终的异常信息显示的是和你没有使用try-catch处理是一样的。
参考代码:
{ 代码块 1 }(Exception ex1){ 日志处理 ); ; }
划重点2-嵌套异常抛出: 将第5行的异常捕获改为: 使用new Exception("test new error message",ex); 通过new一个新的异常,将ex放入内部异常参数中即可保留原始异常信息。
参考代码:
{ 代码块1 }(Exception ex){ 日志处理 ); throw new Exception(test error,ex) }
当然也可以使用多层嵌套。
效果如下:
参考道友文章:C#中try catch中throw ex和throw方式抛出异常有何不同
总结
以上是小编为你收集整理的C#中try catch中throw ex和throw方式抛出异常有何不同_异常捕获堆栈丢失问题 C#中try catch中throw ex和throw方式抛出异常有何不同全部内容。
如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。
我们今天的关于Mocha / Chai expect.to.throw 没有捕捉到抛出的错误和未捕获异常该怎样处理的分享已经告一段落,感谢您的关注,如果您想了解更多关于.net – 无法加载Exchange powershell管理单元:“Microsoft.Exchange.Data.Directory.Globals”的类型初始化程序抛出异常、Airbnb Challenge and Expectations、c# – 顶级异常没有捕捉到任何东西、C#中try catch中throw ex和throw方式抛出异常有何不同_异常捕获堆栈丢失问题 C#中try catch中throw ex和throw方式抛出异常有何不同的相关信息,请在本站查询。
本文标签: