C#: Try catch block

If an application handles exceptions that occur during the execution of a block of application code, the code must be placed within a try statement and is called a try block.

Application code that handles exceptions thrown by a try block is placed within a catch statement and is called a catch block.

Here using the previous example, we roll out a simple try catch exception block.

using System;
using System.Diagnostics;
using System.ComponentModel;

namespace GetProcess
{
    /// <summary> 
    /// Shell for the sample. 
    /// </summary> 
    class MyProcess
    {
        void BindToRunningProcesses()
        {
            // Get the current process.
            Process currentProcess = Process.GetCurrentProcess();
            Console.WriteLine(currentProcess.ProcessName);

            try
            {
                Process[] localByName = Process.GetProcessesByName("notepad");
                Console.WriteLine(localByName[0].ProcessName);
            }
            catch
            {
                Console.WriteLine("Notepad not running");
            }


            // Get a process on the local computer, using the process id.  

            try
            {
                Process localById = Process.GetProcessById(6132);
                Console.WriteLine(localById.ProcessName);
            }
            catch
            {
                Console.WriteLine("Process id 6132 not running");
            }
        }

        static void Main()
        {
            MyProcess myProcess = new MyProcess();
            myProcess.BindToRunningProcesses();
            Console.ReadKey();
        }
    }
}

trycatch

Series Navigation<< C#: Checking if a process is running
C#: Enumeration >>