DEV Community

Cover image for Play safe without Try Catch...
Anders Persson
Anders Persson

Posted on • Updated on

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

Top comments (1)

Collapse
 
marqitos profile image
Marcos Porto Mariño

It is always advisable to try to throw exceptions, this is a more efficient and faster code example, than if a try/catch had been added.

Happy coding!