Thursday, March 10, 2016

Extract Line Number from Exception


Get the line number from Exception Class. Following code will give you Line number where exception is raised.

         private static int GetLineNum(Exception mexcption)
        {
            // Get stack trace for the exception with source file information
            var trace = new StackTrace(mexcption, true);

            // Get the very first stack frame
            var frame = trace.GetFrame(0);

            // Extract the line no from frame
            var line = frame.GetFileLineNumber();
            return line;
        }

You need to put pdb file along with exe.
You can use it like that

 private void ProceeEachFile()
        {           
            try
            {
               /* Some Code */
                throw new Exception("Some Error");
              /*Some Code */
             
            }
            catch (Exception ex)
            {
                var LineNum = GetLineNum(ex)
                throw new Exception(ex.Message + " Line Num -" + LineNum +"-->");
            }
        }

           In final method 
private void ByWorksheet(object ob)
        {         
           
            try
            {
              ProceeEachFile();
            }
           
            catch (Exception ex)
            {
                var line = GetLineNum(ex);
                String sLogData += ex.Message + " Line Num "+ line +"\n";
                MessageBox.Show(sLogData);
            }
           
        }


No comments:

Followers

Link