DEV Community

Babak K. Shandiz
Babak K. Shandiz

Posted on • Originally published at babakks.github.io on

2 1

Handle/Raise Exceptions with Little to No Further Processing [RE#10]

Exceptions may occur anywhere, even inside a catch (or except in Python) block. It’s not a wrong presumption that people expect them less in there. Anyway, beware of the code you put in these blocks because when an exception occurs you just don’t want to make things worse.

One safe approach to prevent faulty codes in those blocks is to ensure that you are not doing any further processing or data manipulation there. In other words, if you’re re-raising the exception (or logging something) try to use raw data.

For instance, look at this listing:

class Student {
  getCourses() {
    // Query student courses from repository
  }
  makeStudentIdentifier() {
    return `${this.lastname.trim()} ${this.firstname.trim()} (#${this.studentNo.trim()})`;
  }

  doSomeProcess() {
    try {
      const courses = this.getCourses();
    }
    catch (e) {
      console.log("Process failed for %s: %s", this.makeStudentIdentifier(), e);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

What if, due to some bug somewhere else, Student.studentNo assigned with a number value instead of a string. Calling trim() on a number object causes another exception, terminating the handling you had in mind (here, logging) and returning the control to the first catch block up on the call stack. Not to mention that the original exception, which should be the actual issue to investigate, got masked and you may easily miss it; though somewhere in the middle of the stack trace will be a faint hint to that. So, it’s safer to appreciate raw values and do things with less processing:

console.log("Process failed for %s %s (%s): %s", this.lastname, this.firstname, this.studentNo, e);
Enter fullscreen mode Exit fullscreen mode

About Regular Encounters

I’ve decided to record my daily encounters with professional issues on a somewhat regular basis. Not all of them are equally important/unique/intricate, but are indeed practical, real, and of course, textually minimal.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay