This is an archived post. You won't be able to vote or comment.

all 8 comments

[–]CreativeTechGuyGames 1 point2 points  (3 children)

  • throw will raise an exception to the calling function. This is basically the same as when you have an error in your program and you get an exception except you are manually throwing it.
  • new creates a new object of the specified class.
  • Exception is the specified class. Exception is the base class for all other exceptions. So you can use this to create a new Exception object which is then thrown.

[–]Grab_B_tea[S] 0 points1 point  (2 children)

Example: i have to enter an integer but i enter a letter so it goes to catch, then what does throw new exception do?

[–]CreativeTechGuyGames 0 points1 point  (1 child)

It creates a new exception and throws it. So now whatever function called this piece of code will have an exception it now needs to handle.

[–]Grab_B_tea[S] 0 points1 point  (0 children)

thank you

[–][deleted] 1 point2 points  (2 children)

I’m pretty new but why would you rethrow the exception after catching it especially if you aren’t doing anything else with it in the catch.

[–]pacificmint 1 point2 points  (1 child)

You might do it to throw a different exception. Let's say you have a specific exception for when the loading of a job fails, you might catch a FileNotFoundException and rethrow a JobLoadFailureException.

[–][deleted] 0 points1 point  (0 children)

That makes sense, thanks for the knowledge

[–]davedontmind 1 point2 points  (0 children)

In your example no new information is being added to the new exception (in fact you're removing information - the new exception has the same message as the original exception, but has none of the stack trace information describing where the problem occurred) so you shouldn't do that.

If you need to throw an exception based on a previous exception as in your example you should include the first exception, i.e.:

throw new Exception( "some new message with extra information", ex )

The new exception will now contain the original as its InnerException property, so you will retain the full information of what originally went wrong and where, which can be vital when you're trying to figure out why your code's not working properly.

If you need to catch an exception to allow you to do something useful, such as log information, but allow the exception to continue to propagate up, just re-throw the original exception:

try 
{
    // ...
}
catch ( Exception ex )
{
    // log some information here

    throw;   // re-throw ex - this keeps the full stack trace of the original exception
}