Abdelrahman Elghoul
Abdelrahman Elghoul

Reputation: 17

How to go from Try to Catch in specific condition in Try

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

Answers (3)

Sunil
Sunil

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

Gholamali Irani
Gholamali Irani

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

tmaj
tmaj

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

Related Questions