Codementor Events

Is try..catch really useful?

Published Oct 05, 2018Last updated Apr 02, 2019
Is try..catch really useful?

I’d like to touch a specific subject that I’ve been asked before a lot of times.

A few weeks back I’ve been asked in my company by one of the developers from my team about ‘try..catch’ error handling and if we supposed to use that in our components?

To be honest – going through my whole developer’s experience and my entire journey as a developer and have never been using try and catch as a way to handle errors. Maybe it was predicted because of projects that I was working on or something else. I just didn’t need to use it, didn’t have a reason for that.

I’m coming from the natural and used on daily basis methodology that shows you how to handle errors without using try and catch approach. It is my personal opinion as a developer and that’s obvious that other developers can have other opinions and at the same time, disagree with me.

What I think is that if you use try..catch methodology, you don’t really know how to control your code flow. You don’t really know what is going to happen next and it doesn’t appear as a good implementation. If you are experienced programmer and you went through hard times in the field, you’re going to get to that point eventually when you realize that having clean, rapid and understandable code for other developers is not enough. You need to have the ability to control the flow – clearly, you need to be convinced and sure about what’s going to happen because coding is not a weather forecast and is not the direction of the wind that can change any moment.

The interesting part of controlling your code flow is that you need to combine three or four elements of good coding practices to be able to say that your code is not a storm that can go to the left or to the right any moment. What did I mean by saying to combine three or four elements?

Coding_flow.jpg

As you can see in the above image – this is how I describe a good code flow in brief. As developers, we should have established that learning is a bread for the breakfast and we should learn how to handle errors without using try..catch while building a small and medium-sized application.

I have mentioned three paragraphs above that coding is not a weather forecast – true, it is not and you are responsible for your own code and what is going to happen with it. In the other hand, you may say – I can’t predict what is going to be returned by the server as a response, then I’m going to use try and catch to handle that. The truth is that in that case, you’re going to choose a lazy way to implement error handling.

What can you do to make it better instead of implementing try and catch straightaway? If you developed a server app for your project, you know what kind of codes and responses will be returned and you have probably handled all of the errors in your server app. If you didn’t do it, you need to make sure that you have received a list of errors that will be returned from the external server after sending the request to API. You need to know that! You can’t use try and catch because you don’t know something, try to inquire it.

Below you can see a simple architecture of handling errors without try and catch:

const getPostCode = (postCodeNum) => {
    const handleErrors = (errorCode) => {
        const errorCodes = {
            '500': handleInternalServerError,
            '404': handleNoneExistent
        };

        return errorCodes[errorCode]();
    };


    fetch(`https://www.url.com/getPostCode?code=${postCodeNum}`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        const errors = data.error;
        const resp = data.response;

        if(errors) {
            handleErrors(errors.code);
        } else {
            handleResponse(resp);
        }
    })
    .catch(error => error);
};

getPostCode(07819283);

I gave my opinion on building small and medium web applications and including try..catch in the code, I’d like to talk about creating a large scale web application. I’m finding it as a completely different terrain to look at because in theory if you’ve got a good control over small/medium application, you’re going to lose the control over large one.

Why does it happen? It happens because the amount of code and complexity increase and we’ve got one module that communicates with other module and then another and another to perform the same action. It is less predictable and you might not know what is going to happen next. In that case, using try and catch is going to be a great idea to prevent the appearance of errors and issue that are unnecessary and weren’t seen during development plus debugging complex issues can be time-consuming & that’s why you should use try..catch while developing large scale application.

Positives:

  • Hide errors from the user
  • Allows to create custom errors
  • Helps to handle unexpected errors

Negatives:

  • Increases laziness among developers
  • Disables usual browser’s error handling mechanism
  • Decreases code readability
  • Increases debugging time
  • Decreases performance of the application

Summarizing, try..catch should be used while developing large-scale applications instead of using it within medium sized projects. I feel like using try..catch in a small/medium sized projects makes developers lazy and doesn’t really helps them to evolve because they don’t challenge themselves that much as they would be not using the following statement.

That would be it in the first blog post of quick thoughts – please, let me know your opinion in the comments down below, give it a like and share it with your friends.

Discover and read more posts from Robert Wozniak
get started
post commentsBe the first to share your opinion
francovici
6 years ago

Great approach !

Lazar Ljubenović
6 years ago

Decreases performance of the application

I live for the day that using try/catch instead of passing around ad-hoc error objects is the bottleneck performance issue in the web.

James
6 years ago

What about async/await? I never used to use try catch until that came along.

Show more replies