C # Assign Name for Try-Catch Error

Everyone uses Try-Catch in C #. I know it.

For instance:

static void Main()
    {
        string s = null; // For demonstration purposes.

        try
        {            
            ProcessString(s);
        }

        catch (Exception e)
        {
            Console.WriteLine("{0} Exception caught.", e);
        }
    }
}

Everything is fine.

But how can I assign a name for a spesific error?

For instance:

try
{
   enter username;
   enter E-Mail;
}
catch
{

}
  • IF username already exists, ErrorMessage→ ("Username already exists")
  • IF E-Mail already exists, ErrorMessage→ ("E-Mail uses")

How can i do this in C#?

Regards,

Soner

+3
source share
6 answers
if(UserNameAlreadyExists(username))
{
   throw new Exception("Username already exists");
}
if(EmailAlreadyExists(email))
{
   throw new Exception("Email already exists");
}

This will answer your question.

However, exception handling should not be used to perform such checks. Exceptions are expensive and are intended for exceptional circumstances when you cannot recover from an error.

+6

, :

throw new Exception("The username already exists");

, , , ; . , - .

+3
try
{
    if (username exists)
    {
        throw new Exception("The Username Already Exist");
    }

    if (e-mail exists)
    {
        throw new Exception("The E-Mail Already Exist");
    }
}
catch(Exception ex)
{
    Console.WriteLine("The Error is{0}", ex.Message);
}
+2

, , - , :

,

try
{
    if user name is exit
    {
        throw new UserNameExistsException("The Username Already Exist");
    }

    if e-mail is already exit
    {
        throw new EmailExistsException("The E-Mail Already Exist");
    }
}
catch(UserNameExistsException ex)
{
    //Username specific handling
}
catch(EmailExistsException ex)
{
    //EMail specific handling
}
catch(Exception ex)
{
    //All other exceptions come here!
    Console.WriteLine("The Error is{0}", ex.Message);
}
+2

- :

if (UsernameAlreadyExcists(username))
{
    throw new Exception("The Username Already Exist");
}
+1

# . #. , Exception, .

using System;
class MyException : Exception
{
  public MyException(string str)
  {
    Console.WriteLine("User defined exception");
  }
}
class MyClass
{
  public static void Main()
  {
    try
    {
      throw new MyException("user exception");
    }
    catch(Exception e)
    {
      Console.WriteLine("Exception caught here" + e.ToString());
    }      
  }
}

, , .

+1
source

All Articles