在JavaScript中不使用throw语句能否抛出自定义错误?
Great question! Let’s break this down based on whether you need a synchronous or asynchronous error:
Asynchronous Custom Error (No throw, eval, Function, or Error keyword)
Yes, you can trigger a catchable exception without writing the throw statement yourself, and even without using the Error keyword. The trick is using async/await with Promise.reject()—since await converts a rejected promise into a thrown exception automatically.
Here’s a working example:
async function triggerCustomError() { // Reject with any custom value (string, object, etc.) await Promise.reject("Oops, this is my custom error message!"); } try { await triggerCustomError(); } catch (e) { console.log("Caught error:", e); // Outputs: Caught error: Oops, this is my custom error message! }
This works because when you await a rejected promise, the JavaScript engine throws the rejection reason into the surrounding try/catch block—no throw statement required. Since we’re rejecting with a plain string, we don’t need the Error keyword at all.
Synchronous Custom Error
Unfortunately, there’s no way to throw a synchronous custom error (with a message or type you control) without using the throw statement. All built-in synchronous exceptions (like ReferenceError, TypeError, etc.) have predefined, uncustomizable messages. For example, accessing null.property throws a TypeError with a fixed message, but you can’t alter that message to something custom without using throw.
Bonus: Using an Error object without the Error keyword
If you want to throw a proper Error instance (for stack traces, etc.) but avoid writing the Error keyword directly, you can access it via the global object using bracket notation:
async function triggerProperError() { // Get the Error constructor without using the keyword const ErrorConstructor = window['Error']; await Promise.reject(new ErrorConstructor("Custom error with stack trace")); } try { await triggerProperError(); } catch (e) { console.log("Error message:", e.message); console.log("Stack trace:", e.stack); }
This still avoids throw, eval, and Function, and skips using the Error keyword explicitly.
内容的提问来源于stack exchange,提问作者Muhammad Salman

