I assume I'm missing something really trivial here but for reason it's not obvious to me. I've always assumed that "finally" always executes, regardless of an exception or not.
Anyway, this code failed to run and I'm not sure why. It gets to i = i/j and throws an DivideByZero exception but I would've thought it would continue and execute the finally statement before stopping.
static void Main(string[] args)
{
int i = 1;
try
{
int j = 0;
i = i / j;
Console.WriteLine("can't get");
}
finally
{
Console.WriteLine("finally ran");
}
}
Take a look at this MSDN try-finally (C# Reference)
From above link:
Usually, when an unhandled exception ends an application, whether or
not the finally block is run is not important. However, if you have
statements in a finally block that must be run even in that situation,
one solution is to add a catch block to the try-finally statement.
Works for me - at least somewhat. When I run this as a console app from the command line, the "Test.exe has stopped working. Windows is looking for a solution" dialog comes up immediately, but then if I hit the "cancel" button, I see "finally ran". If I let the initial dialog run to completion and just get left with Debug or Close, then hitting Close will terminate the process immediately, and hitting Debug obviously brings up a debugger.
EDIT: Mark Hall's answer explains the behaviour in more detail. I'll leave this answer up as it contains experimental results, but look at Mark's answer :)
Mark's answer says what happens, but I thought I'd mention why:
I believe this is to allow for any external handlers to handler the exception to be handled before the finally block is executed. (For example, when a debugger is attached, it can try to break at the point of exception, allowing you to continue before the finally block starts running.)
If the finally block was executed beforehand, then you couldn't handle the exception in a debugger.
try this:
static void Main(string[] args)
{
int i = 1;
try
{
int j = 0;
i = i / j;
Console.WriteLine("can't get");
}
catch(Exception ex){
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("finally ran");
}
Console.WriteLine("Press enter to exit...");
Console.ReadLine();
}
I think you might need a catch to catch the exception before finally will run.
Related
I'm running a boost::thread which is interrupted from somewhere else in my program.
auto my_thread = boost::thread(&threadedFunction, this);
Is using a function-try-block like this
void threadedFunction() try {
// do stuff
} catch (boost::thread_interrupted &) {
// handle error
}
equivalent to using a try-catch block encompassing the entire function?
void threadedFunction() {
try {
// do stuff
} catch (boost::thread_interrupted &) {
// handle error
}
}
They may not be equivalent, since my_thread can be interrupted before the try block is entered, and in that case, the program would crash. That being said, I'm not sure if this is possible.
Are both chunks of code equivalent?
Yes, but not for constructor bodies.
That's why function-try-block was invented:
The primary purpose of function-try-blocks is to respond to an exception thrown from the member initializer list in a constructor by logging and rethrowing, modifying the exception object and rethrowing, throwing a different exception instead, or terminating the program.
Side note: thread interruption
Boost's thread interruption mechanism is cooperative, not asynchronous (like POSIX signals). That means that, no between { and try { there cannot be an interruption:
https://www.boost.org/doc/libs/1_54_0/doc/html/thread/thread_management.html#thread.thread_management.this_thread.interruption_point
Even if were fully asynchronous, then still it would not make any sense to reason about the "difference" because there would not be any happens-before relationship anyways, so both outcomes could occur in both situations anyways (it's timing dependent regardless).
I am working on a small tool to schedule p4 sync daily at specific times.
In this tool, I want to display the outputs from the P4API while it is running commands.
I can see that the P4API.net has a P4Callbacks class, with several delegates: InfoResultsDelegate, TaggedOutputDelegate, LogMessageDelegate, ErrorDelegate.
My question is: How can I use those, I could not find a single example online of that. A short example code would be amazing !
Note: I am quite a beginner and have never used delegates before.
Answering my own questions by an example. I ended up figuring out by myself, it is a simple event.
Note that this only works with P4Server. My last attempt at getting TaggedOutput from a P4.Connection was unsuccessful, they were never triggered when running a command.
So, here is a code example:
P4Server p4Server = new P4Server(syncPath);
p4Server.TaggedOutputReceived += P4ServerTaggedOutputEvent;
p4Server.ErrorReceived += P4ServerErrorReceived;
bool syncSuccess = false;
try
{
P4Command syncCommand = new P4Command(p4Server, "sync", true, syncPath + "\\...");
P4CommandResult rslt = syncCommand.Run();
syncSuccess=true;
//Here you can read the content of the P4CommandResult
//But it will only be accessible when the command is finished.
}
catch (P4Exception ex) //Will be caught only when the command has completely failed
{
Console.WriteLine("P4Command failed: " + ex.Message);
}
And the two methods, those will be triggered while the sync command is being executed.
private void P4ServerErrorReceived(uint cmdId, int severity, int errorNumber, string data)
{
Console.WriteLine("P4ServerErrorReceived:" + data);
}
private void P4ServerTaggedOutputEvent(uint cmdId, int ObjId, TaggedObject Obj)
{
Console.WriteLine("P4ServerTaggedOutputEvent:" + Obj["clientFile"]);
}
while adding custom font in my app, it's crashing some time.
But most of the time it get executed smoothly.
i'm using following code.
try {
// Get the typeface
ShravyaApp.appTypeFace = Typeface.createFromAsset(getApplication().getAssets(),
"kadage.ttf");
Log.d("font","in type="+ShravyaApp.fontName);
Log.d("font","type face="+ShravyaApp.appTypeFace);
}
catch (Exception e)
{
ShravyaApp.appTypeFace = Typeface.createFromAsset(getApplication().getAssets(),
"kadage.ttf");
Log.d("font","in catch typr="+ShravyaApp.fontName);
Log.d("font","type face="+ShravyaApp.appTypeFace);
//Log.e(TAG, "Could not get typeface '" + + "' because " + e.getMessage());
e.printStackTrace();
}
The Error i'm getting is :
NullPointerException
at android.graphics.Typeface.nativeCreateFromAsset(Native Method)
at android.graphics.Typeface.createFromAsset(Typeface.java:280)
This could be IO Exceptions in the nativeCreateFromAsset. Also this can be because you are calling this method before Activity onCreate().
Any way try using retry mechanism with 100 milliseconds sleeping between retries, there is no reason that it will not work, unless some bug in the user device.
Why place the same code in both try and catch?
I suggest you use a Typface-cache (example here) and if your app really requires the font, you may want to refactor your method into a recursive one and as Babibu said, pause in between.
I am guessing getApplication() is the function that returns a null pointer. It needs to be called in the onCreate(), not in the constructor. We need more context to be sure.
Also you can set a breakpoint catching null pointer exceptions in the debug mode.
I am using LWUIT ResrouceEditor(latest SVN code revision 1513) to generate a UI State machine.
I want to show a wait screen when a long running command is invoked by a user using a button on the current form. I believe I can use the asynchronous option when linking the command on the button. I have setup a form in which I have a button which should invoke the asynchronous command. In command selection for that button, I have set the action to show the wait screen form and have marked the command as asynchronous. However when I use the asynchronous option, the code shows the wait screen, but after that it throws a NullPointerException.
As per my understanding, once you mark a command as asynchronous, it will call the following methods from a different thread where you can handle its processing.
protected void asyncCommandProcess(Command cmd, ActionEvent sourceEvent);
protected void postAsyncCommand(Command cmd, ActionEvent sourceEvent);
However this methods are not getting called and it throws a NullPointerException.
When I looked at the LWUIT code, in UIBuilder.java(lineno. 2278), I see that it constructs the new thread for an asynchronous command as follows:
new Thread(new FormListener(currentAction, currentActionEvent, f)).start();
But when running it through Debugger I see that currentAction and currentActionEvent are always null. And hence when the FormListener thread starts running, it never calls the above two async command processing methods. Please see the listing of the run() method in the UIBuilder.java(line no. 2178)
public void run() {
if(currentAction != null) {
if(Display.getInstance().isEdt()) {
postAsyncCommand(currentAction, currentActionEvent);
} else {
asyncCommandProcess(currentAction, currentActionEvent);
// wait for the destination form to appear before moving back into the LWUIT thread
waitForForm(destForm);
}
} else {
if(Display.getInstance().isEdt()) {
if(Display.getInstance().getCurrent() != null) {
exitForm(Display.getInstance().getCurrent());
}
Form f = (Form)createContainer(fetchResourceFile(), nextForm);
beforeShow(f);
f.show();
postShow(f);
} else {
if(processBackground(destForm)) {
waitForForm(destForm);
}
}
}
}
In the above method, since the currentAction is null, it always goes into the else statement and since the nextForm is also null, it causes the NullPointerException.
On further look at the UIBuilder.java code, I noticed what is causing the NullPointer exception. It seems when the FormListner is created, it is passed currentAction and currentActionEvent, however they are null at that time. Instead the code should be changed as follows(starting at line 2264):
if(action.startsWith("#")) {
action = action.substring(1);
Form currentForm = Display.getInstance().getCurrent();
if(currentForm != null) {
exitForm(currentForm);
}
Form f = (Form)createContainer(fetchResourceFile(), action);
beforeShow(f);
/* Replace following with next lines for fixing asynchronous command
if(Display.getInstance().getCurrent().getBackCommand() == cmd) {
f.showBack();
} else {
f.show();
}
postShow(f);
new Thread(new FormListener(currentAction, currentActionEvent, f)).start();
*/
new Thread(new FormListener(cmd, evt, f)).start();
return;
}
Can lwuit development team take a look at the above code, review and fix it. After I made the above change, the asynchronous command processing methods were invoked.
Thank you.
Thanks for the information, its probably better to use the issue tracker for things like this (at http://lwuit.java.net).
I will make a similar change although I don't understand why you commented out the form navigation portion.
To solve your use case of a wait screen we have a much simpler solution: Next Form. Just show the wait screen and in it define the "Next Form" property.
This will trigger a background thread to be invoked (processBackground callback) and only when the background thread completes the next form will be shown.
I'm having a very frustrating problem. I have a c# win application. When I have clicked the button, the program closes itself after executed the click event handler. Even if I have debugged the code unfortunately I can't see any error, It just quits the program.
Where am I going wrong?
Here is the Code:
private void btnOpenFolder_Click(object sender, EventArgs e)
{
DialogResult dg = fd1.ShowDialog();
if (dg == DialogResult.OK)
{
lblInput.Text = fd1.SelectedPath;
btnOpenFolder.Enabled = false;
timerCallback = new TimerCallback(tmrQualityEvent);
tmrQuality = new System.Threading.Timer(timerCallback, null, 0, 1000);
Thread qualityThread = new Thread(new ThreadStart(QualityMapOpenFolder));
qualityThread.Start();
QualityMapOpenFolder();
}
}
void QualityMapOpenFolder()
{
fileList.Clear();
string path = lblInput.Text;
if (Directory.Exists(path))
{
foreach (var file in Directory.GetFiles(path))
{
if (Path.GetExtension(file) != ".kml")
{
fileList.Add(file);
}
}
SetProgressBarValue(0);
ChangeFileNameLabel(fileList[0]);
FileName = fileList[0];
}
else
SetText("Please make sure you have correctly set the open folder path!", true);
dataListQuality = GetInputData();
SetText("Calculated Data has been created, please click process files...", false);
SetProcessButtonStatus(true);
}
Attach an event handler to the UnhandledException handler and log it. Should help you to find out why your application is crashing.
Update: Now that you have posted some code:
You seem to update UI elements from another thread which you start. You should access UI components only from the thread on which they were created (usually the main thread). Consider using a BackgroundWorker
You start the QualityMapOpenFolder method on a thread and then you also call it after you started the thread - this seems a bit weird and has probably some unexpected side effects.
The common reason for this kind of behavior is unhandled exception in background thread. To prevent program.
#ChrisWue wrote on how to detect this kind of exceptions.
Also, often Windows Application log provides an insight on unhandled errors.
See here how to prevent killing app in this case.