Home > Back-end >  C# Try/Catch statement, am i doing this right?
C# Try/Catch statement, am i doing this right?

Time:07-11

using System;

namespace Something
{
    class MainProgram
    {
        public static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Hello? am I working?")
            }
            catch
            {
                Console.WriteLine("Nah I ain't working");
            }
        }
    }
}

I'm just poking about with C#, and I wanted to try errorchecking and whatnot. There's the code and the console. Does Catch{} just not do syntax errors?

CodePudding user response:

Catch only catches runtime errors. This can be seen as you specify what it will catch and there is no type you specify in the catch that represents syntax errors.

If there is a syntax error, there is no program that runs the catch in the first place.

And yes, you can use a catch without specifying the type of Exception, but that's just a shortcut for catching all errors which derive from Exception so it is a shortcut for catch (Exception e)

CodePudding user response:

Try/Catch is not for SyntaxErrors, but Runtime errors. You can do

try{
  // Code here
} catch(Exception e){
  // log the exception
} finally{
  // code here will run no matter what (with or without errors)
}

As you can see, catch can optionally take a Exception parameter that can help you log it better. In your case, you will catch all exceptions, but you don't have a reference to the exception.

Try catch is usually used for cases like reading from a file/database, making web requests, etc. All these things may fail for external reasons but they are Syntax-wise correct.

CodePudding user response:

Dont feel stupid for asking...

            try
            {
                //do stuff
            }
            catch (Exception ex)
            {
                //error ocurred
                Console.WriteLine(ex.Message);
            }
            finally
            {
                //do stuff even if no error occurs
            }

The "catch" part may be more "complete" according to the type of exception you expect.

CodePudding user response:

   public void Do()
    {
        try
        {
            //try something
        }
        catch (Exception e) // catch exception in e
        {
            Console.WriteLine(e); // print e to console or do what ever you want with it
            throw; //then enter what you want to do next after an exception happen, if you do nothing the runtime will go out of the try/catch and will move on to the next commend.
        }
    }
  •  Tags:  
  • c#
  • Related