Difference Between 'Throw' and 'Throw New Exception()'

Difference between 'throw' and 'throw new Exception()'

throw; rethrows the original exception and preserves its original stack trace.

throw ex; throws the original exception but resets the stack trace, destroying all stack trace information until your catch block.



NEVER write throw ex;


throw new Exception(ex.Message); is even worse. It creates a brand new Exception instance, losing the original stack trace of the exception, as well as its type. (eg, IOException).

In addition, some exceptions hold additional information (eg, ArgumentException.ParamName).

throw new Exception(ex.Message); will destroy this information too.

In certain cases, you may want to wrap all exceptions in a custom exception object, so that you can provide additional information about what the code was doing when the exception was thrown.

To do this, define a new class that inherits Exception, add all four exception constructors, and optionally an additional constructor that takes an InnerException as well as additional information, and throw your new exception class, passing ex as the InnerException parameter. By passing the original InnerException, you preserve all of the original exception's properties, including the stack trace.

Difference between throw new Exception and new Exception ?

new Exception() means create an instance (same as creating new Integer(...))
but no exception will happen until you throw it...

Consider following snippet:

public static void main(String[] args) throws Exception {
foo(1);
foo2(1);
}

private static void foo2(final int number) throws Exception {
Exception ex;
if (number < 0) {
ex = new Exception("No negative number please!");
// throw ex; //nothing happens until you throw it
}

}

private static void foo(final int number) throws Exception {
if (number < 0) {
throw new Exception("No negative number please!");
}

}

the method foo() will THROW an exception if the parameter is negative but
the method foo2() will create an instance of exception if the parameter is negative

what is the difference between throwing a new exception within a body of a method and throwing the exception in the header of the method

public abstract String test(String value) throw new testException;

does not make sense. The closest thing you can do is write

public abstract String test(String value) throws testException;

which indicates that test is a method that could throw a testException. If testException is not a RuntimeException, then it must be declared like that. But adding throws testException to the method signature only says that the method could throw that exception, it doesn't actually do the throwing.

throw new std::exception vs throw std::exception

The conventional way to throw and catch exceptions is to throw an exception object and to catch it by reference (usually const reference). The C++ language requires the compiler to generate the appropriate code to construct the exception object and to properly clean it up at the appropriate time.

Throwing a pointer to a dynamically allocated object is never a good idea. Exceptions are supposed to enable you to write more robust code in the face of error conditions. If you throw an exception object in the conventional manner you can be sure that whether it is caught by a catch clause naming the correct type, by a catch (...), whether it is then re-thrown or not it will be destroyed correctly at the appropriate time. (The only exception being if it is never caught at all but this is a non-recoverable situation whichever way you look at it.)

If you throw a pointer to a dynamically allocated object you have to be sure that whatever the call stack looks like at the point you want to throw your exception there is a catch block that names the correct pointer type and has the appropriate delete call. Your exception must never be caught by catch (...) unless that block re-throws the exception which is then caught by another catch block that does deal correctly with the exception.

Effectively, this means you've taken the exception handling feature that should make it easier to write robust code and made it very hard to write code that is correct in all situations. This is leaving aside the issue that it will be almost impossible to act as library code for client code that won't be expecting this feature.

Is there a difference between throw and throw ex ?

Yes, there is a difference.

  • throw ex resets the stack trace (so your errors would appear to originate from HandleException)

  • throw doesn't - the original offender would be preserved.

     static void Main(string[] args)
    {
    try
    {
    Method2();
    }
    catch (Exception ex)
    {
    Console.Write(ex.StackTrace.ToString());
    Console.ReadKey();
    }
    }

    private static void Method2()
    {
    try
    {
    Method1();
    }
    catch (Exception ex)
    {
    //throw ex resets the stack trace Coming from Method 1 and propogates it to the caller(Main)
    throw ex;
    }
    }

    private static void Method1()
    {
    try
    {
    throw new Exception("Inside Method1");
    }
    catch (Exception)
    {
    throw;
    }
    }

What is the difference between `throw 'foo'`, `throw Error('foo')`, `throw new Error('foo')`?

throw is an expression which halts the function and generates an exception. Whatever directly follows throw is passed along in the exception. Think of it as a function with syntax sugar, so instead of writing throw('message') you write throw 'message'. throw new Error('message') is just like throw 'message' except an object is being passed along instead of a string literal.

There is no difference between throw Error('message') and throw new Error('message'): many of the core JavaScript objects allow for the creation of a new object without the new constructor and Error happens to be one of them.

That being said, you should always use throw new Error('message'). The Error object contains a stacktrace and other useful debugging information which is lost when you use a string literal. Creating objects using ES6 classes requires the use of new and extending Error via a class is the only way to preserve stacktraces. Creating a custom error class makes error handling much more uniform.

See Also: extremely elaborate illustration.

What is the difference between `throw new Error` and `throw someObject`?

The difference between 'throw new Error' and 'throw someObject' in javascript is that throw new Error wraps the error passed to it in the following format −

{ name: 'Error', message: 'String you pass in the constructor'
}

The throw someObject will throw the object as is and will not allow any further code execution from the try block, ie same as throw new Error.

Here is a good explanation about The Error object and throwing your own errors

The Error Object

Just what we can extract from it in an event of an error? The Error object in all browsers support the following two properties:

  • name: The name of the error, or more specifically, the name of the constructor function the error belongs to.

  • message: A description of the error, with this description varying depending on the browser.

Six possible values can be returned by the name property, which as mentioned correspond to the names of the error's constructors. They are:

Error Name          Description

EvalError An error in the eval() function has occurred.

RangeError Out of range number value has occurred.

ReferenceError An illegal reference has occurred.

SyntaxError A syntax error within code inside the eval() function has occurred.
All other syntax errors are not caught by try/catch/finally, and will
trigger the default browser error message associated with the error.
To catch actual syntax errors, you may use the onerror event.

TypeError An error in the expected variable type has occurred.

URIError An error when encoding or decoding the URI has occurred
(ie: when calling encodeURI()).

Throwing your own errors (exceptions)

Instead of waiting for one of the 6 types of errors to occur before control is automatically transferred from the try block to the catch block, you can also explicitly throw your own exceptions to force that to happen on demand. This is great for creating your own definitions of what an error is and when control should be transferred to catch.



Related Topics



Leave a reply



Submit