if i am running code
try
{
line one
line 2
line 3
.
.
.
.
}
catch(Exception x)
{
}
now if exception occurs at any line i dont know and we do some stuff in catch so that exception dose not occur again at that line now we need to goback to line from where exception occurred and execute same line how can we do that?
Assuming this is Java, you can't do that - once the exception is thrown, nothing in the rest of the try block will be executed. You would have to use multiple try/catch blocks to explicitly do what you want:
try {
line one
} catch (Exception x) {
fixup line one
}
try {
line 2
} catch (Exception x) {
fixup line 2
}
...etc.
That sort of defeats the purpose of a try catch. If you catch an exception, you should handle the error. If you want to continue where you left off, the best way would probably be to put code in a finally block. This code will always run if there is an exception or no exception is thrown.
try {
//some exception prone code
}
catch(Exception e) {
//handle exception
}
finally {
//Always runs after exception caught or if no exception thrown
}
You don't. If you fixed the problem, you should run the entire block again. The point of a try block is that it has everything you need to perform a certain task. An exception makes everything after that in the task impossible. If you need to clean up, say, open file descriptors, you can use a finally block; but you really need to just fix the problem and try again or die with a good error message.
You can stick the try/catch block inside of a loop like so:
bool done = NO;
while ( ! done ) {
try {
done = YES;
} catch {
}
}
This causes the entire block to be re-executed. If you want to resume where you left off then you need to track your state along the way:
bool done = NO;
int state = 0; // setup some constants, kStateA = 0, kStateB = 1, etc:
while ( ! done ) {
try {
switch ( state ) {
case kStateA: line 1; ++state; // fall through
case kStateB: line 2; ++state;
// etc.
}
done = YES;
} catch {
}
}
The above code, simplified to be more in line with your question looks like this (though the state-machine concept is still the underlying principle):
bool done = NO;
int lineNumber = 1;
while ( ! done ) {
try {
switch ( lineNumber ) {
case 1: line 1; ++lineNumber; // fall through
case 2: line 2; ++lineNumber; // fall through
// etc.
}
done = YES;
} catch {
}
}
Related
I have a requirement that is columns validation in the Script component. If the column value found null it should be stopped task with red cross mark and then the task should be the exit.
I have used below code to fail the script component task. But it's not stopping the task, it passing the next code line.
DTSExecResult result;
result = DTSExecResult.DTSER_FAILURE;
If you just force an error and prevent further execution from the Script Component you can throw an error as done below. However you'll want to make sure this is defined well enough to distinguish it from any other errors that may occur.
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
if (Row.Column1_IsNull)
{
throw new Exception("Error Message");
}
}
Dts.TaskResult = (int)ScriptResults.Failure;
return this from the script task
Here is my main method
public static void main (String[] args) {
Scanner console = new Scanner(System.in);
Intro();
try {
userInput(console);
} catch (InputMismatchException e) {
System.out.println("Not a number; try again.");
}
}
I would like the userInput(console); to run again even if the Exception was found. The method userInput(console); runs a program that asks for the radius of a circle and calculates its diameter, circumference, and area. I tried using a while loop outside of the try/catch statement but I don't know what I should use as conditions. Comment if you would like to see the userInput(console) method and I will post that as well.
Using a while loop with a condition is ok. Just remember that the condition serves as a flag to define if the iteration should carry on or stop, in particular because a certain condition was met. In this case, your condition is defined by the user's input validation result. Assuming you used a while like this:
while(someCondition) {
try {
userInput(console);
} catch (InputMismatchException e) {
System.out.println("Not a number; try again.");
}
}
Your someCondition variable should be a boolean initialized in true that is set to false when the input is valid or, in your case, when no exception is thrown. You can also set it to false after a certain amount if iterations. If you set someCondition to false, the next time the while evaluates someCondition it is false, and the iteration ends.
Another approach is to use a while(true) loop and end the iteration by using a break statement. It achieves the same in this case, but they're essentially different:
The someCondition approach doesn't cut the current iteration, it lets it finish the processing (considering you have something in the loop that must be done with the valid input, for example).
By using a break statement, that iteration is interrupted and the while loop ends without executing the rest of the code encased inside of it.
I'm trying to do something that's arguably a bad idea, but I think it's still possible. I'm trying to override how WP8 handles the Back Button and implement it myself. I theorize that if I:
The Plan
Only ever create one "Frame" and "Page" in the entire application
Always handle PhoneApplicationPage.BackKeyPress myself unless they were about to back out of the application.
The Repro
Here's a sample project that has the crash
The code
..then it should work. However, my attempts are being thwarted by Windows Phone. Here's the code:
// This basically happens on PhoneApplicationService.OnLaunched
_viewModelChanged.StartWith(ViewModel).Where(x => x != null).Subscribe(vm => {
var page = default(IViewFor);
var frame = RootVisual as PhoneApplicationFrame;
// Find the initial PhoneApplicationPage for the app
page = RxApp.GetService<IViewFor>("InitialPage");
// Depending on how we're being signalled (i.e. if this is cold start
// vs. resume), we need to create the PhoneApplicationFrame ourselves
if (frame == null) {
frame = new PhoneApplicationFrame() {
Content = page,
};
}
page.ViewModel = vm;
var pg = page as PhoneApplicationPage;
if (pg != null) {
pg.BackKeyPress += (o, e) => {
if (ViewModel.Router.NavigationStack.Count <= 1 ||
ViewModel.Router.NavigateBack.CanExecute(null)) {
return;
}
e.Cancel = true;
ViewModel.Router.NavigateBack.Execute(null);
};
}
// Finally, set Application.RootVisual
RootVisual = frame;
});
Sadness
This works great, until right after this code executes, where a DispatcherItem queued by the framework crashes the app:
System.NullReferenceException occurred
Message: A first chance exception of type 'System.NullReferenceException' occurred in Microsoft.Phone.ni.dll
Microsoft.Phone.ni.dll!Microsoft.Phone.Controls.PhoneApplicationPage.InternalOnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e) Unknown
Microsoft.Phone.ni.dll!Microsoft.Phone.Controls.PhoneApplicationPage.Microsoft.Phone.Controls.IPhoneApplicationPage.InternalOnNavigatedFromX(System.Windows.Navigation.NavigationEventArgs e) Unknown
Microsoft.Phone.ni.dll!System.Windows.Navigation.NavigationService.RaiseNavigated(object content, System.Uri uri, System.Windows.Navigation.NavigationMode mode, bool isNavigationInitiator, Microsoft.Phone.Controls.IPhoneApplicationPage existingContentPage, Microsoft.Phone.Controls.IPhoneApplicationPage newContentPage) Unknown
Microsoft.Phone.ni.dll!System.Windows.Navigation.NavigationService.CompleteNavigation(System.Windows.DependencyObject content, System.Windows.Navigation.NavigationMode mode) Unknown
Microsoft.Phone.ni.dll!System.Windows.Navigation.NavigationService.ContentLoader_BeginLoad_Callback(System.IAsyncResult result) Unknown
Microsoft.Phone.ni.dll!System.Windows.Navigation.PageResourceContentLoader.BeginLoad_OnUIThread(System.AsyncCallback userCallback, System.Windows.Navigation.PageResourceContentLoader.PageResourceContentLoaderAsyncResult result) Unknown
Microsoft.Phone.ni.dll!System.Windows.Navigation.PageResourceContentLoader.BeginLoad.AnonymousMethod__0(object args) Unknown
[Native to Managed Transition]
mscorlib.ni.dll!System.Delegate.DynamicInvokeImpl(object[] args) Unknown
System.Windows.ni.dll!System.Windows.Threading.DispatcherOperation.Invoke() Unknown
System.Windows.ni.dll!System.Windows.Threading.Dispatcher.Dispatch(System.Windows.Threading.DispatcherPriority priority) Unknown
System.Windows.ni.dll!System.Windows.Threading.Dispatcher.OnInvoke(object context) Unknown
System.Windows.ni.dll!System.Windows.Hosting.CallbackCookie.Invoke(object[] args) Unknown
System.Windows.RuntimeHost.ni.dll!System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(System.IntPtr pHandle, int nParamCount, System.Windows.Hosting.NativeMethods.ScriptParam* pParams, System.Windows.Hosting.NativeMethods.ScriptParam* pResult) Unknown
So, I've solved this - my code was problematic because I didn't grok how WP8 works :) Here's what I understand now, which may also be wrong but I'll write it anyways
How your WP8 app is initialized:
The OS creates your App class via rehydrating App.xaml.cs
This means, your constructor gets run, and as part of that, you create a PhoneApplicationFrame
Creating a PhoneApplicationFrame seems to also set a global static variable (same thing happens with creating PhoneApplicationService in the App.xaml, it sets PhoneApplicationService.Current).
NavigationService then attempts to recreate a XAML View via a resource string (i.e. '/MainPage.xaml'). Either it will recreate the one that was previously tombstoned, or if not, it defaults to the one in your WMAppManifest (this is the part I didn't understand).
PhoneApplicationFrame.Navigated gets called by NavigationService - this is where you can actually start doing stuff, including most importantly, setting Application.RootVisual, which will send the Loading... screen away
PhoneApplicationService.Launched or PhoneApplicationService.Activated finally fires, once basically everything is set up, depending how your app was woken up.
Found the issue. Well, the tip of the iceberg.
The code of the InternalOnNavigatedFrom method is:
internal override void InternalOnNavigatedFrom(NavigationEventArgs e)
{
PhoneApplicationPage content = e.Content as PhoneApplicationPage;
string str = ((content == null) || (content.Title == null)) ? string.Empty : content.Title;
PerfUtil.BeginLogMarker(MarkerEvents.TH_ONNAVIGATEDFROM_PAGE, string.Format("{0},{1},{2}", (base.Title == null) ? "" : base.Title, e.NavigationMode, str));
this.OnNavigatedFrom(e);
PerfUtil.EndLogMarker(MarkerEvents.TH_ONNAVIGATEDFROM_PAGE, string.Format("{0},{1},{2}", (base.Title == null) ? "" : base.Title, e.NavigationMode, str));
DeviceStatus.KeyboardDeployedChanged -= new EventHandler(this.OnKeyboardDeployedChanged);
Task rootTask = ApplicationHost.Current.RootTask;
rootTask.OnVisibleRegionChange = (ITask.VisibleRegionChanged) Delegate.Remove(rootTask.OnVisibleRegionChange, new ITask.VisibleRegionChanged(this.OnVisibleRegionChange));
Task task2 = ApplicationHost.Current.RootTask;
task2.OnSipVisibilityChange = (ITask.SipVisibilityChange) Delegate.Remove(task2.OnSipVisibilityChange, new ITask.SipVisibilityChange(this.OnSipVisibilityChange));
this._lastSipHeight = 0.0;
this._dictionary = null;
}
After a bit of debugging, I concluded that neither e or Application.Current.RootTask were null. After scratching my head, I looked at the code of the KeyboardDeployedChanged event handler:
public static event EventHandler KeyboardDeployedChanged
{
[SecuritySafeCritical] add
{
if (KeyboardDeployedSubscription == null)
{
KeyboardDeployedSubscription = new SubscriptionHandler(DeviceTypes.KeyBoard);
}
KeyboardDeployedSubscription.Changed += value;
}
[SecuritySafeCritical] remove
{
KeyboardDeployedSubscription.Changed -= value;
}
}
This code is poorly written. If the remove part of the handler is called before the add, KeyboardDeployedSubscription will be null and an exception will be raised. To test my theory, I subscribed to the event in App's constructor:
public App()
{
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
DeviceStatus.KeyboardDeployedChanged += (sender, e) => { };
And sure enough, the exception was gone. Now, to understand why your code is triggering this issue, I backtraced to which part of the framework is supposed to subscribe to the event. The only candidate is the InternalOnNavigatedTo method.
Therefore, your issue is that OnNavigatedFrom is called even though OnNavigatedTo was never called.
Since you are strungling with the built-in auto navigation of Windows Phone to the page defined in WMAppManifest.xml, I tried to remove the auto navigation and it basically worked (no exception).
I just replaced
<DefaultTask Name="_default" NavigationPage="MainPage.xaml" />
with
<DefaultTask Name="_default" />
Not sure if this solves your problem but it at least doesn't crash anymore.
LoaderMax uses the following function in their DisplayObjectLoader.as class which is under loader/core :
Although they have put the forced GC under a Try/Catch block. Flash Player 11 still manages to crash on it. Any ideas about this?
protected static function _forceGCHandler(event:Event):void {
if (_gcCycles == 0) {
_gcDispatcher.removeEventListener(Event.ENTER_FRAME, _forceGCHandler);
_gcDispatcher = null;
} else {
_gcCycles--;
}
try {
new LocalConnection().connect("FORCE_GC");
new LocalConnection().connect("FORCE_GC");
} catch (error:Error) {
}
}
Perhaps you could edit the forced gc out and use System.pauseForGCIfCollectionImminent(0.25)
To connect 2 different connections you can try:
new LocalConnection().connect("FORCE_GC");
new LocalConnection().connect("FORCE_GC1");
But I don't know will this force the GC.
If I have a method such as:
private function testMethod(param:string):void
{
// Get the object that called this function
}
Inside the testMethod, can I work out what object called us? e.g.
class A
{
doSomething()
{
var b:B = new B();
b.fooBar();
}
}
class B
{
fooBar()
{
// Can I tell that the calling object is type of class A?
}
}
Sorry the answer is no (see edit below). Functions received a special property called arguments and in AS2 it used to have the property caller that would do roughly what you want. Although the arguments object is still available in AS3 the caller property was removed from AS3 (and therefore Flex 3) so there is no direct way you can do what you want. It is also recommeded that you use the [...rest parameter](http://livedocs.adobe.com/flex/3/langref/statements.html#..._(rest)_parameter) language feature instead of arguments.
Here is a reference on the matter (search for callee to find the relevant details).
Edit: Further investigation has shown that it is possible to get a stack trace for the current executing function so if you are lucky you can do something with that. See this blog entry and this forum post for more details.
The basic idea from the blog post is you throw an Error and then catch it immediately and then parse the stack trace. Ugly, but it may work for you.
code from the blog post:
var stackTrace:String;
try { throw new Error(); }
catch (e:Error) { stackTrace = e.getStackTrace(); }
var lines:Array = stackTrace.split("\n");
var isDebug:Boolean = (lines[1] as String).indexOf('[') != -1;
var path:String;
var line:int = -1;
if(isDebug)
{
var regex:RegExp = /at\x20(.+?)\[(.+?)\]/i;
var matches:Array = regex.exec(lines[2]);
path = matches[1];
//file:line = matches[2]
//windows == 2 because of drive:\
line = matches[2].split(':')[2];
}
else
{
path = (lines[2] as String).substring(4);
}
trace(path + (line != -1 ? '[' + line.toString() + ']' : ''));
Is important to know that stackTrace is only available on the debugger version of Flash Player. Sorry! :(
I'd second the idea of explicitly passing a "callingObject" parameter. Unless you're doing really tricky stuff, it should be better for the caller to be able to supply the target object, anyway. (Sorry if this seems obvious, I can't tell what you're trying to accomplish.)
To add to the somewhat ambiguous first paragraph of James: the arguments property is still available inside a Function object, but the caller property has been removed.
Here's a link to the docs: http://livedocs.adobe.com/flex/3/langref/arguments.html
This might help someone, I'm not sure... but if one is using an Event this is possible using the e.currentTarget as follows:
private function button_hover(e:Event):void
{
e.currentTarget.label="Hovering";
}