简体   繁体   中英

Is it a good practice to throw exceptions on errors when parsing internal language?

I'm working on a JS library, as a part of it, I built a parser for small sort of a markup language to enable users to use more complicated expressions. I wanted to know if it is a good practice to throw an exception if there is an error in internal expression syntax and let users use the function within the try/catch block, or if it's better for example to return false and inform the user that there was a parsing error some other way (possibly console)? I can't really tell if throwing an exceptions is common practice when building a library, I know that jQuery for example throws some errors in its source, but jQuery is huge framework-like library so I would expect that, but is it common for small size libraries?

The problem with throwing exceptions on parse errors is that once you throw an exception, it is very difficult to resume the parse. That means that the parser intends to give up as soon as it hits the first syntax error; in other words, that it expects the user to fix one error at a time.

It's possible that you currently don't do any error recovery, so this might not bother you. But it should.

Are you certain that you're not going to want to try error recovery, particularly after listening to your users grumbling about how they have to try the parse dozens or hundreds of times to find all of their errors? And when you do eventually start to implement error recovery, will you be happy about having to find and change every place where the parser in order to change the way it is called?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM