抛出JavaScript异常的标准做法是什么? [英] What are the standard practices for throwing JavaScript Exceptions?

查看:101
本文介绍了抛出JavaScript异常的标准做法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

w3schools说,异常可以是字符串,整数,布尔或对象,但是给出的示例不会使我成为一个好的做法,因为异常类型检查是通过字符串比较完成的。这是JavaScript中异常处理的首选方法吗?是否有内置异常类型(如NullPointerException)? (如果是,他们是什么,他们使用什么样的继承,他们比其他选择更喜欢?)

解决方案

例外可以是你喜欢的任何东西。



在其他语言中,例外应该是实例,然后 catch 语句选择哪个例外可以通过实例的类来捕获,哪些可以通过。



然而,JavaScript没有此功能。您只能捕获所有异常,然后查看该值来决定如何处理。如果您不想处理异常,则必须手动重新抛出捕获的值。 (这不可避免地使 catch 语句相当混乱。)



您可以决定将异常作为对象实现并对其进行比较与 instanceof 。或者您可以使用唯一的不透明值进行比较。或者你甚至可以直接输入字符串或数字,如果你真的想要。


是否有内置的异常类型(如NullPointerException)? / p>

种类。 ECMAScript定义了一些标准错误类:错误及其子类型 EvalError RangeError ReferenceError SyntaxError TypeError 的URIError 。但是有浏览器实现问题,例如 try {nonexistentvar; } 在IE下给出 TypeError ,而不是 ReferenceError 。而且还有很多其他浏览器特定的异常,特别是在处理DOM时。



直接使用这些对象并不是传统的,并且试图将它们子类化是凌乱的(因为JavaScript没有类系统)。您会倾向于坚持自己定义的异常,以改用自己的应用程序。例外情况在JavaScript中并不广泛。


w3schools says that exceptions can be strings, integers, booleans, or objects, but the example given doesn't strike me as good practice, since exception type checking is done through string comparison. Is this the preferred method of exception handling in JavaScript? Are there built-in exception types (like NullPointerException)? (if so, what are they, what kind of inheritance do they use, and are they preferred over other options?)

解决方案

Exceptions can be anything you like.

In other languages, exceptions should be instances, and then the catch statement chooses which exceptions to catch and which to let fall through by the class of the instance.

JavaScript, however, does not have this feature. You can only catch all exceptions, and then look at the value to decide what to do with it. If you don't want to handle an exception you have to re-throw the caught value manually. (This inevitably makes catch statements rather messy.)

You can decide to implement your exceptions as objects and compare them with instanceof. Or you could have unique opaque values to compare against. Or you can even throw straight strings or numbers if you really want to.

Are there built-in exception types (like NullPointerException)?

Kind of. ECMAScript defines some standard error classes: Error and its subtypes EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError. However there are browser implementation issues, for example try { nonexistentvar; } gives TypeError under IE instead of ReferenceError. And there are many other browser-specific exceptions particularly when dealing with the DOM.

It's not traditional to use these objects directly, and trying to subclass them is messy (since JavaScript doesn't have a class system as such). You would tend to stick to your own defined exceptions for your own apps' use instead. Exceptions are not that widely-used in JavaScript.

这篇关于抛出JavaScript异常的标准做法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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