Use a String from a "try catch" in another "try catch"

RobinJ 276 Reputation points
2020-12-07T23:09:29.247+00:00

Hello,
how can I use a String inside a "try catch" outside in another "try catch"?
I need the string "server_token_string".

string server_token_string;

                try
                {
                    using (StreamReader sr = new StreamReader(@$"{localappdata}\Liquid Aqua\API\server_token.txt", Encoding.Default))
                    {
                        StringBuilder server_tokens = new StringBuilder();

                        // schreibt Zeile für Zeile auf den StringBuilder bis das Ende der Datei erreicht ist
                        while (!sr.EndOfStream)
                            server_tokens.AppendLine(sr.ReadLine()); fortschritt_label.Content = "Reading Server File..."; progress_bar.Value = 6;
                        server_token_string = server_tokens.ToString();
                    }
                }
                catch
                {

                }


                //Überprüfung Token
                try
                {
                    if (server_token_string.Contains(token_eingabe))
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,363 questions
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2020-12-08T00:01:23.637+00:00

    As long as the string is declared outside of the try/catch blocks and you initialize the string, then all should be fine:

    string server_token_string = null;
    
    try
    {
        ...
        server_token_string = "ackbar";
    }
    catch
    {
        ...
    }
    
    try
    {
        ...
        if (server_token_string != null && server_token_string.Contains("ack"))
        {
        }
    }
    catch
    {
        ...
    }
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Timon Yang-MSFT 9,576 Reputation points
    2020-12-08T02:14:08.587+00:00

    When we use class members (property and field), we don't need to assign initial values to them, it will be done automatically. But local variables are different from class members, you must manually assign values to them.

    I think this may have misled you.

    When an exception occurs in the first try block, the code may not reach the 12th line of the displayed code, which will cause the server_token_string to be in an uninitialized state, so it cannot be used in the second try block.

    Take a look at the explanation in this link to understand why it is designed this way:
    Are C# uninitialized variables dangerous?


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments