我如何区分不同类型的异常? [英] How would I differentiate between different types of exceptions?

查看:73
本文介绍了我如何区分不同类型的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习JavaScript,到目前为止没问题,但我很难在JS中找到对Exception机制的一个很好的解释。

I'm starting to learn JavaScript, so far no problem but I have a hard time finding a good explanation of the Exception mechanism in JS.

看起来很相似对于C ++,JS允许抛出每个对象,而不仅仅是抛出一个Exception对象(可能是由于它的动态特性)。

It seems similar to C++, JS allows to throw about every object, instead of just throwing an Exception object (probably due to it's dynamic nature).

throw 'An error occured.';

有效,以及

throw new Exception('An error occured.');

catch 最后两者似乎都像他们的Java等效。尽管如此,我不知道有哪些被广泛接受的关于异常的最佳实践。

catch and finally both seem to work like their Java equivalent. Still, I don't know what are widely accepted best practices regarding exceptions.

因此,例如,抛出string类型的对象是否合法,如:

So, for example, is it legit to throw objects of type string, like:

throw 'An error occured';

我如何区分不同类型的例外?

How would I differentiate between different types of exceptions?

推荐答案

我建议尽量避免try / catch,而是专注于以旧方式检查错误(返回类型,确保变量在使用之前正确初始化等等),因为异常在这里不太可能发生在C ++中或特别是Java或.NET。

Throwing and catching exceptions is pretty expensive, and with JavaScript, you're primarily going to get exceptions in cases like when you try to parse a JSON string that is malformatted. I would suggest avoiding try/catch as much as possible and instead focus on checking for errors the old fashion way (return types, making sure variables are properly initialized before using them, etc.) since exceptions are less likely to happen here than in C++ or especially Java or .NET.

Andy E的推荐是一个很好的实际处理它们,但一般来说,你应该尝试防御性地编写JavaScript代码,这样你甚至不需要try / catch。请记住,即使是与Java或C#相比,Chrome中的JITed JavaScript(速度最快的引擎)仍然很慢,更不用说C ++,因此在JavaScript中,这些语言中的任何代价都可能更高。

Andy E's recommendation is a good one for actually handling them, but in general, you should try to write JavaScript code defensively so that you don't even need try/catch. Remember, even JITed JavaScript in Chrome (fastest engine) is still slow as heck compared to Java or C#, to say nothing of C++, so anything that is expensive in those languages is likely to be even more so in JavaScript.

这篇关于我如何区分不同类型的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆