C # Error handling catch blocks

Why, in most cases, we are not advised to catch bugs like Exception, but traps that we expect as developers. Is there success in capturing common mistakes or is it recommended in terms of best practice?

  try
  {
        // Do something
  }
  catch(Exception e)
  {
        //Log error
  }
0
source share
6 answers

Best practice is to catch a specific exception first and then move on to more general ones.

Exception Handling (C # Programming Guide)

catch . catch , catch . catch, . catch , catch, , . ( ).

:

, "", , .

catch NullReferenceException. NullReferenceException, , null, . , .

string str = null;
try
{
   Console.WriteLine(str.Length)
}
catch(NullReferenceException ne)
{
    //exception handling. 
}

.

if(str != null)
   Console.WriteLine(str.Length);

EDIT:

, . , , IMO, , , , , , . . ( ) , , , " ", .

(, - ), , .

, ASP.Net Application_Error, .

2: OP:

, , , SQLException

- , . , , SqlException, .

+8

, . Exception , , . , , :)

, Exception, , . .

+4

( Vexing) .

; , , , .

• , . .

• , , "Try" , . vexing, .

• , ; . .

+2

, , . , DataTable, .

public DataRow AccessFirstRow(DataTable dt)
{
  try
  {
    return dt.Rows[0];
  }
  catch (Exception e)
  {
    //There isn't a first row or dt is null
  }
}

public DataRow AccessFirstRow(DataTable dt)
{
  if(dt != null)
   if(dt.Rows.Count > 0)
     return dt.Rows[0];
  //If we can't access dt, then don't
  return null;
}

:

.

, , , , , , .

+1

. , , , , , / .

+1

, . (), (, , ).

If the code in the block trythrows different types of exceptions, you can handle some exceptions within the same method and rethrow others to handle them in the caller's method (since in this context you have resources to handle these exceptions).

+1
source

All Articles