Exception catching - general doubts

I am learning CSharp. I have some doubts about handling exceptions. Trust me to improve my coding knowledge.

Suppose I build a code segment:

try { 

        SomeWork();  
        return success;
    }
    catch (someException ex)
    { 
        throw new ExceptionDetails(ex);
        return failure; 
    }
    catch(AnotherException exp)
    {
        throw new ExceptionDetails(exp);
        return failure;
    }
    finally
    {
        CleanUpStuff();
    }

Questions:

(1) Is it possible to use the return statement after a throw (throwing exception)?

(2) Is throwing an exception an ugly practice? When do I just need to throw an exception? Do I need to use "throw" to send only a custom exception?

(3)

    try
    {
        SomeWork();
    }
    catch(StringIndexOutOfBound ex)
    {
        throw;
    }

Using an anonymous expression statement inside catch is good practice?

+3
source share
5 answers

1) ( ) , . , .

2) , ... . , .

3) # 3, - . - , "" (??), .

+3

: . !

+3

, return .

, finally.

throw ex

reset .

, .

+1
+1

1) return , .

2) , . .

public void readFile()
{
    try
    {
        // Perform IO action
    }
    catch ( FileNotFoundException ex )
    {
        // Perform error recovery e.g. create a default file   
    }
    catch ( Exception ex )
    {
        // Cant perform any error recovery at this level so throw the exception to allow the calling code to deal with it
        throw;
    }
 }

, , , , IO. , - if, . , , , .

, , , . , !

3) , - "" , , , .

+1

Source: https://habr.com/ru/post/1719489/


All Articles