Reputation: 17
I have a specific condition in try want it to be in catch if happened
string x;
try {
if(x==null)
//send to catch
}
catch {
//Show messagebox
}
I tried throw new Exception but found most of answers here recommend not to use and i have more than 1 condition i want to send each separated to handle in different catch so is this possible or I should just spam if else ?
what I realy trying to do is that
I have 2 TextBox want to make sure they not empty and 2 DateTime Picker want to make sure 1always before the other (start date and end date)
Upvotes: 1
Views: 216
Reputation: 3424
Point to be noted, throwing exceptions in your code slows down the performance of your application. So always avoid throwing non-fatal exceptions. Throw exceptions only when you cannot handle the consequences.
For everything else that you should handle using either if
or switch
(if you need to test multiple cases).
Example:
string x;
if(x == null) { /* show message */ }
if(x == "") { /* show another message */ }
if(x == "1") { /* show yet another message */ }
Using switch:
string x = null;
switch (x)
{
case null:
Console.WriteLine("string is null");
break;
case "":
Console.WriteLine("string is empty");
break;
case "1":
Console.WriteLine("string is 1");
break;
}
By the way for string is null or empty, use string.IsNullOrEmpty
or string.IsNullOrWhiteSpace
Upvotes: 3
Reputation: 4350
you can use throwing an exception into try to go straight to catch.
see below code: SOME_System_Exception
can be any system exceptions
string x;
try {
if(x==null)
throw new SOME_System_Exception();
}
catch {
//Show messagebox
}
Upvotes: 2
Reputation: 34947
I think if
is all you need.
if(x==null) {
//do what you need to do
} else if (x.Value < 3) {
//do something else
} (...)
Upvotes: 0