Play safe without Try Catch...
Anders Persson
Posted on August 20, 2023
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);
above work well, until one day when we get..
string payment = "saknas";
var amount = double.Parse(payment);
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!
}
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
Posted on August 20, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.