Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

javascript - Throwing strings instead of Errors

Since we can throw anything with the throw keyword in Javascript, can't we just throw an error message string directly?

Does anyone know any catch in this?

Let me add some background to this: Very often, in the JavaScript world, people rely on parameter checking as opposed to using the try-catch mechanism, so it makes sense to only throw fatal errors with throw. Still, to be able to catch some system Errors, I have to use a different class for my own errors and instead of creating a subclass of Error, I think I should just use String.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

While it is okay possible to throw any value, it is generally considered poor form to throw anything other than an instance of Error or one of its subclasses. There are several reasons for this:

  1. Catching code may expect the thrown object to have the usual message, stacktrace, and name properties that appear on Errors.
  2. Lack of a stacktrace makes debugging problematic, especially in the case of uncaught exceptions / unhandled rejections. E.g. Debugging an "Uncaught [Object object]" error can be particularly painful.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...