How to Get the Line Number Which Threw Exception

How can I get the line number which threw exception?

If you need the line number for more than just the formatted stack trace you get from Exception.StackTrace, you can use the StackTrace class:

try
{
throw new Exception();
}
catch (Exception ex)
{
// Get stack trace for the exception with source file information
var st = new StackTrace(ex, true);
// Get the top stack frame
var frame = st.GetFrame(0);
// Get the line number from the stack frame
var line = frame.GetFileLineNumber();
}

Note that this will only work if there is a pdb file available for the assembly.

How can I get the line number where the exception was thrown using Thread.UncaughtExceptionHandler?

Try

e.getStackTrace()[0].getLineNumber();

The first element in the stack trace is the most recently called method (the top of the call stack).

There are also methods to get the class, method and file name.

If the e you get in the UncaughtExceptionHandler does not work well for you (because it wraps the real exception), you can try e.getCause() and look at that stack trace.

Show line number in exception handling

Use ex.ToString() to get the full stack trace.

You must compile with debugging symbols (.pdb files), even in release mode, to get the line numbers (this is an option in the project build properties).

How to get the method name and line number in Exception in ASP Core 5

A simple call to ToString() on exception will give you the complete information needed. For example when we run the following code:

public static void Main()
{
try
{
//my code
throw new ArgumentException();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}

The output would be somewhat like:

System.ArgumentException: Value does not fall within the expected range.
at ConsoleApp.Program.Main() in C:\Users\USER\source\Playground\ConsoleApp1\Program.cs:line 20

where Main() is the method name and 20 is the line number.

To get the format as required in question we can write a wrapper around the exception and fetch the line number from it:

using System;
using System.Reflection;

namespace ConsoleApp
{
class Program
{
public static void Main()
{
try
{
//my code
throw new ArgumentException();
}
catch (Exception ex)
{
Console.WriteLine(MethodBase.GetCurrentMethod().Name + "/" + GetLineNumber(ex));
}
}

public static int GetLineNumber(Exception ex)
{
var lineNumber = 0;
const string lineSearch = ":line ";
var index = ex.StackTrace.LastIndexOf(lineSearch);
if (index != -1)
{
var lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length);
if (int.TryParse(lineNumberText, out lineNumber))
{
}
}
return lineNumber;
}
}
}

Note: In the extract line method, we are fetching the top most exception. This comes in handy when we have a chain of exceptions in our stack trace.

How to get error line number of code using try-catch

Try this simple hack instead:

First Add this (extension) class to your namespace(most be toplevel class):

public static class ExceptionHelper
{
public static int LineNumber(this Exception e)
{

int linenum = 0;
try
{
//linenum = Convert.ToInt32(e.StackTrace.Substring(e.StackTrace.LastIndexOf(":line") + 5));

//For Localized Visual Studio ... In other languages stack trace doesn't end with ":Line 12"
linenum = Convert.ToInt32(e.StackTrace.Substring(e.StackTrace.LastIndexOf(' ')));

}

catch
{
//Stack trace is not available!
}
return linenum;
}
}

And its done!Use LineNumber method whenever you need it:

try
{
//Do your code here
}
catch (Exception e)
{
int linenum = e.LineNumber();
}

When I catch an exception, how do I get the type, file, and line number?

import sys, os

try:
raise NotImplementedError("No error")
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)

Is there a way to get the line number where an exception was thrown?

You need 10g to use

DBMS_OUTPUT.put_line('Error in '|| $$plsql_unit || ' at ' || $$plsql_line);

also look into using

DBMS_UTILITY.format_error_backtrace

there is an article in Oracle Magazine from april '05 by Steven Feuerstein:

http://www.oracle.com/technetwork/issue-archive/2005/05-mar/o25plsql-093886.html

Cheers, niels

How to know the line number from where the exception is coming from in PHP

I just pasted code to get the line number and function name in my select query.

Following is the code:

Exception("MySQL error $mysqli->error <br> Query:<br> $sql", $msqli->errno);

The select query will look like this after you add the above line of code:

final protected function select($args = array(), $is_die = false){
try {

$this->sql = "SELECT ";
if (isset($args['fields'])) {
if (is_array($args['fields'])) {
$this->sql .= implode(', ', $args['fields']);
} else {
$this->sql .= $args['fields'];
}
} else {
$this->sql .= " * ";
}
$this->sql .= " FROM ";
if (!isset($this->table) || empty($this->table)) {
throw new Exception("Table not set");
}
$this->sql .= $this->table;

/*Join Query*/
if (isset($args['join']) && !empty($args['join'])) {
$this->sql .= " ".$args['join'];
}
/*Join Query*/

if (isset($args['where']) && !empty($args['where'])) {
if (is_array($args['where'])) {
$temp = array();
foreach ($args['where'] as $column_name => $data) {
if (!is_array($data)) {
$data = array(
'value' => $data,
'operator' => '=',
);
}
$str = $column_name.' '.$data['operator'].' :'.str_replace('.', '_', $column_name);
$temp[] = $str;
}
$this->sql .= " WHERE ".implode(' AND ', $temp);
} else {
$this->sql .= " WHERE ".$args['where'];
}
}

/*Group*/
if (isset($args['group_by']) && !empty($args['group_by'])) {
$this->sql .= " GROUP BY ".$args['group_by'];
}
/*Group*/

/*Order*/
if (isset($args['order_by']) && !empty($args['order_by'])) {
$this->sql .= " ORDER BY ".$args['order_by'];
} else {
$this->sql .= " ORDER BY ".$this->table.".id DESC";
}
/*Order*/

/*Limit*/
if (isset($args['limit']) && !empty($args['limit'])) {
if (is_array($args['limit'])) {
$this->sql .= " LIMIT ".$args['limit'][0].",".$args['limit'][1];
} else {
$this->sql .= " LIMIT ".$args['limit'];
}
}
/*Limit*/
$this->stmt = $this->conn->prepare($this->sql);
if (is_array($args['where']) || is_object($args['where'])){

foreach ($args['where'] as $column_name => $data) {
$value = is_array($data) ? $data['value'] : $data; //check if passed where statement was an array, fetch value if so
if (is_int($value)) {
$param = PDO::PARAM_INT;
}elseif (is_bool($value)) {
$param = PDO::PARAM_BOOL;
}elseif (is_null($value)) {
$param = PDO::PARAM_NULL;
}else {
$param = PDO::PARAM_STR;
}
if ($param) {
$this->stmt->bindValue(":".str_replace('.', '_', $column_name), $value, $param);
}
}

}

if ($is_die) {
echo $this->sql;
debugger($this->stmt);
debugger($args, true);
}

$this->stmt->execute();
$data = $this->stmt->fetchAll(PDO::FETCH_OBJ);
return $data;
} catch (PDOException $e) {

error_log(
date('Y-m-d h:i:s A').", Select Query: ".$e->getMessage()."\r\n"
, 3, ERROR_PATH.'/error.log');
return false;
} catch (Exception $e) {
error_log(
date('Y-m-d h:i:s A').", General: ".$e->getMessage()."\r\n"
, 3, ERROR_PATH.'/error.log');
Exception("MySQL error $mysqli->error <br> Query:<br> $sql", $msqli->errno);
return false;
}
}

For more information, programmers can visit this link: PHP Manual



Related Topics



Leave a reply



Submit