Play safe without Try Catch...

anderspersson

Anders Persson

Posted on August 20, 2023

Play safe without Try Catch...

The most dangerous thing you can do, in programming (besides running out of coffee) is type conversion, especially when you run on so-called "happy flow", which means that you always think nothing can go wrong, it's better to always think that it can go wrong and writes its code after that. Example: conversion of a text to integers, i.e. we get the numbers as text.

string payment = "100.5"
var amount = double.Parse(payment);
Enter fullscreen mode Exit fullscreen mode

above work well, until one day when we get..

string payment = "saknas";
var amount = double.Parse(payment);
Enter fullscreen mode Exit fullscreen mode

This gives a exception and program stops.

So can we find out when our "payment" is not correct?
Yes, you can put a try catch around, but it will be a lot of code, there is one easier way, with .. TryParse

string payment = "saknas"

if( !double.TryParse(payment, out amount)) 
{
  handling error, write to log!
}
Enter fullscreen mode Exit fullscreen mode

TryParse returns true if the conversion went well, and false if it went wrong, without throwing an error that causes your program to stop. Now you can easily take care of the error, without having to write a lot of try-catch handling for it.

Happy coding!
Anders

💖 💪 🙅 🚩
anderspersson
Anders Persson

Posted on August 20, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Demystifying Algorithms: Doubly Linked Lists
datastructures Demystifying Algorithms: Doubly Linked Lists

November 29, 2024

Demystifying Algorithms: Circular Linked Lists
datastructures Demystifying Algorithms: Circular Linked Lists

November 29, 2024

Demystifying Algorithms: Singly Linked Lists
datastructures Demystifying Algorithms: Singly Linked Lists

November 29, 2024

i18n e ASP.NET Core Web API
csharp i18n e ASP.NET Core Web API

November 28, 2024