Why does Try-Catch require curly braces

Just curious: Why is the syntax for try catch in C# (Java also?) hard coded for multiple statements? Why doesn't the language allow:

int i;
string s = DateTime.Now.Seconds % 2 == 1 ? "1" : "not 1";
try
   i = int.Parse(s);
catch
   i = 0;

The example is for trivial purposes only. I know there's int.TryParse.

Score: 56
Tags: c#, try-catch
Views: 6423
Date posted: 10/22/2010

Why can't control leave a finally statement?

When I place a return inside the block of a finally statement, the compiler tells me:

Control cannot leave the body of a finally clause

Example:

try
{
}
catch
{
}
finally
{
    return;
}

Why is this?

Score: 52
Tags: c#, try-catch
Views: 17380
Date posted: 4/16/2013

Does finally ensure some code gets run atomically, no matter what?

Assume I'm going to write a Python script that catches the KeyboardInterrupt exception to be able to get terminated by the user using Ctrl+C safely

However, I can't put all critical actions (like file writes) into the catch block because it relies on local variables and to make sure a subsequent Ctrl+C does not break it anyway.

Would it work and be good practice to use a try-catch block with empty (pass) try part and all the code inside the finally part to define this snippet as "atomic, interrupt-safe code" which may not get interrupted mid-way?

Example:

try:
    with open("file.txt", "w") as f:
        for i in range(1000000):
            # imagine something useful that takes very long instead
            data = str(data ** (data ** data))
            try:
                pass
            finally:
                # ensure that this code is not interrupted to prevent file corruption:
                f.write(data)

except KeyboardInterrupt:
        print("User aborted, data created so far saved in file.txt")
        exit(0)

In this example I don't care for the currently produced data string, i.e. that creation could be interrupted and no write would be triggered. But once the write started, it must be completed, that's all I want to ensure. Also, what would happen if an exception (or KeyboardInterrupt) happened while performing the write inside the finally clause?

Score: 6
Tags: python, try-catch, try-catch-finally, try-finally, keyboardinterrupt
Views: 664
Date posted: 4/21/2016

Try - Catch return strategy

When using try-catch in methods, if you want you application to continue even if errors come along, is it okay to return the default value as return through the catch block, and log the error for later review?

For Example:

public static string GetNameById(int id)
{
    string name;
    try
    {
        //Connect to Db and get name - some error occured
    }
    catch(Exception ex)
    {
        Log(ex);
        name = String.Empty;
    }

    return name;
}

Example 2:

public static string GetIdByName(string name)
{
    int id;
    try
    {
        //Connect to Db and get id- some error occured
    }
    catch(Exception ex)
    {
        Log(ex);
        id = 0;
    }

    return id;
}

Is it okay to return any default value (depending on the return type of the method ...???) so that the application logic that required the result from this method do not crash and keeps going ....

Thanks in advance...

Regards.

Score: 5
Tags: c#, asp.net
Views: 6911
Date posted: 1/20/2011

C++ try-catch block doesn't catch hardware exception

I'm examining hardware and software exceptions in visual studio 2013. I know that I can catch hardware exceptions by setting 'Enable C++ Exceptions' option to /EHa (Yes with SEH Exceptions). I'm trying to catch the following exceptions:

EXCEPTION_ARRAY_BOUNDS_EXCEEDED - didn't catch

EXCEPTION_ACCESS_VIOLATION - caught

EXCEPTION_INT_OVERFLOW - didn't catch

EXCEPTION_INT_DIVIDE_BY_ZERO - caught

This is an example of code.

try {
    a = std::numeric_limits<int>::max();
    a += 5;
}
catch (...){

    std::cout << "EXCEPTION_INT_OVERFLOW Exception Caught" << std::endl;
    exit(1);
}

try {
    int h = 0;
    b = b / h;
}
catch (...){

    std::cout << "EXCEPTION_INT_DIVIDE_BY_ZERO Exception Caught" << std::endl;
    exit(1);
}

It catches only divide by zero exception. Is this dependent of processor, or there is something else? One more little question, is there any difference between debug and release builds?

Score: 5
Tags: windows, visual-studio, exception, operating-system, seh
Views: 1248
Date posted: 4/19/2015


2


© 2021 Search Overflow
Contributions licensed under cc by-sa