Exceptions Are Your Friends

Photo by Nong Vang on Unsplash

When We Throw Exception

1 — Changing the Exception Type

Suppose we write a method called Split. Suppose we send the total amount to be paid and the list of people who will share the bill as parameters in this method. Let’s imagine that our method results in returning the amount a person has to pay. If there is nobody to participate in the payment, the division operation executed in C# language creates an exception of the DivideByZeroException type. In this case, by changing the exception type, we can both write our own explanation and choose a more appropriate error type. In our example scenario, although the reason for the error is that the number cannot be divided by zero, we can better represent the situation with an exception type indicating that the parameter given to the method is not valid.

2 — Unprocessable State

Let’s say we write a calculator as a desktop program. Suppose we return a result by summing the values ​​in the TextBox when the add button is pressed. If the values ​​we have received are not numbers, we are not able to continue the operation. In such cases where we cannot continue the process, we can create an exception and terminate the process.

3 — Unexpected Situation

In some cases, we may not be able to execute the operation even if the parameter we get is in the appropriate format and value range. Such exceptional situations will also be one of the scenarios that we create exceptional cases.

Throwing Exception vs Returning Operation Result

Throwing exceptions or returning operation results with an error code are two scenarios that we can use interchangeably. Both of these scenarios have some disadvantages. In this part of the article, we will address these disadvantages.

Disadvantages of Returning Operation Result

1 — Code Length

Disadvantages of Throwing Exception

1 — Increased Response Time

  • When we work with an existing city (CityId = 1), our service structure that uses exception works with a slightly better performance. This is because it deals with less control blocks.
  • When we make a transaction with a city that does not exist (CityId = 0), it takes much more time to complete our transaction due to the cost of throwing an exception object.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adem Catamak

Adem Catamak

var software = ConvertFrom(caffeine)