What does C# throw and finally means in lay men terms? [closed] - c#

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Say you are running a program,
and it meets a "THROW" statement... what happens?
Will the program stop? Will it continue?
And what's "FINALLY" for?
Please I appreciate an explanation in simple words

if program meeets throw instruction it will throw an exception.
Will your application stop or continue running depends on will you handle that exception ot not with catch instruction.
finally, instead, is introduced to guarantee the execution of the containing code inside that block either exception was thrown or not.

See the MSDN documentation for throw here: http://msdn.microsoft.com/en-us/library/1ah5wsex.aspx
In brief, throw raises an exception. If you are in a try-catch block then it will be caught, if not your program may crash.
The finally block executes after the try-catch block regardless of whether there was an exception which was thrown (and caught).

The throw statement is used to signal the occurrence of an anomalous situation (exception) during the program execution. Usually the throw statement is used with try-catch or try-finally statements. When an exception is thrown, the program looks for the catch statement that handles this exception.
The finally block is useful for cleaning up any resources allocated in the try block as well as running any code that must execute even if there is an exception. Control is always passed to the finally block regardless of how the try block exits.
Throw: http://msdn.microsoft.com/en-us/library/1ah5wsex(v=vs.80).aspx
Finally: http://msdn.microsoft.com/en-us/library/zwc8s4fz(v=vs.80).aspx

You find a lot of information here:
http://msdn.microsoft.com/en-us/library/ms173160(v=vs.80).aspx
Exceptions have the following properties:
When your application encounters an exceptional circumstance, such as a division by zero or low memory warning, an exception is generated.
Use a try block around the statements that might throw exceptions.
Once an exception occurs within the try block, the flow of control immediately jumps to an associated exception handler, if one is present.
If no exception handler for a given exception is present, the program stops executing with an error message.
If a catch block defines an exception variable, you can use it to get more information on the type of exception that occurred.
Actions that may result in an exception are executed with the try keyword.
An exception handler is a block of code that is executed when an exception occurs. In C#, the catch keyword is used to define an exception handler.
Exceptions can be explicitly generated by a program using the throw keyword.
Exception objects contain detailed information about the error, including the state of the call stack and a text description of the error.
Code in a finally block is executed even if an exception is thrown, thus allowing a program to release resources.

Related

What happens if an exception is thrown during stack unwinding? [duplicate]

This question already has answers here:
What happens if an exception occurs in Catch block in C#. Also what would be the caller result in that case
(7 answers)
What happens if a finally block throws an exception?
(11 answers)
Closed 2 years ago.
When managed code is being executed by a .Net CLR, what happens if a second exception is thrown whilst the runtime is unwinding the stack due to an initial exception?
This doesn't refer to rethrowing an exception from a Catch block. It covers situations where an exception is thrown whilst the CLR is in the process of unwinding the stack.
In C++, this would cause the program to terminate, but I can't find any documentation about the behaviour in .Net.

Catching generic non-fatal exceptions [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Conventional wisdom suggests we should only catch the specific exception types we're expecting:
try
{
int.Parse(str); //I am aware of TryParse(), this is just for the sake of example
}
catch (FormatException ex)
{
Console.WriteLine (ex);
}
catch (OverflowException ex)
{
Console.WriteLine (ex);
}
However, sometimes we don't really care which exception happened (as long as it's not fatal), maybe because we just want to let the user know an error occurred. In these cases we can do something like this:
try
{
Foo();
}
catch (Exception ex)
{
if (IsCriticalException(ex))
{
Environment.FailFast("System Error", ex);
}
Console.WriteLine ("Error running Foo: {0}", ex);
}
Where IsCriticalException can be implemented similarly to System.ClientUtils.IsCriticalException. I am generally in favor of this approach for a couple of reasons:
Some methods can throw many exception types and it can be cumbersome to catch them all. For example, File.Open can throw nine different types of exceptions.
Some methods can throw undocumented exceptions. This is either due to lacking documentation, or due to some bug. For example, ICommunicationObject.Close can actually throw ArgumentException due to an obscure bug. Some methods cannot even know statically which exceptions could be thrown by them, since they load other modules / plugins dynamically. Supposedly they could wrap all such "external" exceptions with their own known exceptions, but I believe not all of them do.
The critics of this approach argue that a method's exceptions are part of its contract. If an exception is thrown that is not part of this contract, we should assume its state is corrupt. We will have also discovered a bug in the method (one we otherwise would not have spotted since we'd have swallowed the unexpected exception). We could then relay this bug to the framework's developers, and this is a win - especially if those developers are in our company, so we've "helped ourselves" so to speak.
I admit, the critics present valid points, but I feel they are a bit idealistic. Practically, I think generic non-fatal exception catching makes sense in a lot of situations. Am I making sense?
Related reading:
How to Design Exception Hierarchies
Vexing exceptions
Conventional wisdom suggests we should only catch the specific exception types we're expecting
Actually, I think you should catch exactly those exceptions, that you can handle. There is no use in catching exceptions just to rethrow them and it does not make sense to let those exceptions pass that you would have had a cure for.
In your above example, I think having a catch-all block would have been fine, after all not converting that string is a recoverable error, no matter what exception pops up (except for OutOfMemoryException, which cannot be handled anyway because any attempt at handling would use memory).

Throwing a New Exception Best Practice [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Is the following good practice and if not what should be done?
catch(Exception e)
{
throw new Exception(e.Message, e);
}
No, this is not good practice if you're throwing another exception of the exact same type with the same message. In doing this, you complicate the stack trace and make debugging more of a pain.
If you're going to throw a new exception, it should differ from the original in some significant way. It should be another type, for example, or in some other way (like a more specific error message) clarify the reason for the exception. If you can't do either of those things, then simply rethrow the current exception using throw;.
Or, even better, don't catch it at all. Rethrowing actually messes up the stack trace a tiny bit as well (the current frame's error location is set to the rethrow point rather than the spot where the exception happened), so if you don't have anything you personally have to do to handle the exception, then hands off -- just let it propagate and let the caller handle it.
Just rethrow the exception that was caught, no need to create a new one.
catch(Exception e)
{
// Do some logging...
throw;
}
Some reading on rethrowing exceptions and implications on the stack trace for it: http://msdn.microsoft.com/en-us/library/ms182363(v=vs.100).aspx
It depends on what you are trying to do. That exact code would be pointless, but something like
catch(Exception ex)
{
throw new ApplicationSpecificException("Error while doing something specific: " + contextualData, ex);
}
will help tremendously while debugging.
If you need do something with the exception before re-throwing it, do this:
catch(Exception e)
{
// Additional handling here
throw;
}
Throw by itself simply re-throws the current exception. If you don't need to handle it here, don't catch it in the first place.
Also, in your example you are catching any type of exception but throwing in its place a generic Exception - probably not very useful.
If the code really is just:
try
{
// something
}
catch(Exception e)
{
throw new Exception(e.Message, e);
}
Just delete the try/catch, it's not doing anything productive. Exchanging throw; for the throw new... is better, but still not productive.
if there's something else going on in the catch, do as Gromer details, and just use throw;

C# why throw errors [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Im not getting the throw keyword, why use it? What are the benefits of it?
As of now I've got this in my UI class:
try
{
Classreference.MethodToRun();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
This works but I guess with throw I could make the method I am calling throw the error instead and catch it in my UI class? But why? What is better about it? Is it done to make the classes more object oriented or what? I am guessing if I just catch the error in my UI class I wont need to change the code if I change the method I am calling, but instead change the error message in the method being changed?
You use throw to indicate that an error has occured or to pass an existing error on to a higher level.
You use catch when you want to handle the error (Exception).
Throwing the exception is an improvement over the older procedural way of handling errors where you would return error codes.
The reason it is better is because you can write your logic for the simple success case, and when things go wrong you simply throw an exception, no error handling in your lower level code. It is then up to the higher levels of the application to decide what to do when a particular exception is throw.
asawyer is right, you need to google and read up on error handling, it is a wide subject and you only really 'get it' after practice, talking, and reading about it. throw is something you probably won't need to use overly often, but you can occasionally use it to stop unwanted behaviour and create clearer errors for programmers using your methods. I know it is quite contrived but take this example:
public string WriteToFile(FileStream fs) {
if (fs == null) {
throw new ApplicationException("you passed a null filestream");
}
// write to file
}
You could just attempt to write the FileStream to a file without validating it, but in doing so you create a more understandable error for anyone consuming your method.
You can use the throw keyword to throw an exception to the higher method.
Using this way, you can ocassionally make a better use of the exception, like closing database-access or something like that.
What you are doing here is effectively masking a lot of information that you could get from the exception.
what you regularly want to do is catch the exception, log the relevant information to some place where you can review it (logfile, db, eventlog) and then either throw(), which will keep you stack trace intact, or throw another "user friendly" exception which is masking the technical implementation.

Handling Exceptions [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am working in a code-base(C# 3.5), which is littered with exception handling blocks which return true/false, when inside in a function which returns 'bool'.
catch (Exception ex) { return false; }
This is not correct practice.I am thinking of logging the exception, and have a local variable(to function) which will be initialized.And, this variable will be returned at the end of function.
What do you think?
The usual accepted way to handle exception is to handle them only if you can do something about it. You can of course handle a generic exception just for log puroposes but you should reraise it once you're done.
Your application logic shouldn't rely on exceptions. If there is absolutely no other way to do it, then at least handle concrete exceptions instead of the generic one...
Personally, I would get rid of all of these catch blocks and let the exception bubble up when it happens.
As you say, using exceptions for application logic is bad practice.
Have a catchall exception handler that will catch all such exceptions and log them and terminate the program (if that's the right thing for this program).
It is highly subjective what you want here.
It is old C-style code to have your functions return a true/false value depending on the function succeding or not. In the C# world, it is alot more common to throw exceptions.
You can debate for a long time which is the right path to choose for your code base.
My general point of view is to stick to the exceptions, they have the advantage that they bubble up and usually require less code. And there is also great support for actually logging uncaught exceptions.
You inherited code where the original programmer just didn't want to deal with errors. As written, the program will simply malfunction (say, not save a record to the database) and there's no way to find out why it malfunctioned. Especially since this is dbase code, this will cause random data corruption and loss of precious data.
You indeed cannot leave the code the way it is. The very first thing you need to do is remove all try/catch statements so the program terminates when there's an error. Add an AppDomain.UnhandledException event handler to log the exception so you know what went wrong. Fix errors you'll encounter by correcting code or validating the data. Do expect this to take time, it is very likely that you'll discover many design problems that were shoved under a doormat before.
That's certainly better than what you've got!
Although I wouldn't recommend using the bool return value as proper exception handling, if there is already a lot of code written that way, going and making sweeping modifications everywhere may not be the best idea.
Throwing an exception is generally better than returning false - an exception can at least give the receiver some clue of what happened and why the failure occurred.
The return value of a method should be the result of a method, or it should throw an exception explaining why the requested operation could not be completed.

Categories