Powershell: non-terminating error become terminating error if raised inside a `try` block - powershell-5.0

I need some pointer to understand this behavior:
'---------------------------------'
$ErrorActionPreference = 'Continue'
function Do-Something {
Invoke-WebRequest 'http://www.notexistanthost.xyz/notexistantpath/'
'first error is non-terminating'
try
{
Invoke-WebRequest 'http://www.notexistanthost.xyz/notexistantpath/'
'never reached'
}
catch
{
'second time the same error becomes terminating and go in catch block'
}
}
Do-Something
A function that usually return a non-terminating error, with the same parameters return generate a terminating error when inside a try block.
Why and when this happens?
Is this something related to every function?

If it works inside a try/catch, it's a terminating error. It's lesser known, but there are 2 kinds of terminating errors, script terminating and command terminating. The try sees the command terminating error and acts on it. '1/0' is also command terminating.
try { 1/0; 'hi' } catch { 'caught' }
caught
"Cannot find path" is not a terminating error:
try { dir foo } catch { 'caught' }
Get-ChildItem: Cannot find path '/Users/js/foo' because it does not exist.

Related

How to skip particular WebElement process when locator is not found?

prinBalAgencyComm.sendKeys(testData.get("agencyCommissionPB"));
prinBalClientRem.sendKeys(Keys.TAB);
prinBalFrom2.sendKeys(testData.get("fromFB2")); //Locator not found
prinBalAgencyCommLast.sendKeys(testData.get("agencyCommissionLastPB")); //how to execute this line without fail
You can handle this by using try catch finally.
try{
//code that can result in an exception
prinBalAgencyComm.sendKeys(testData.get("agencyCommissionPB"));
prinBalClientRem.sendKeys(Keys.TAB);
prinBalFrom2.sendKeys(testData.get("fromFB2"));
}catch(Exception e)
{
//actions you want to take in case your locator isnt found or another exception occurs
System.out.println("Exception occured" + e.getMessage());
}finally
{ //the line to be executed without fail
prinBalAgencyCommLast.sendKeys(testData.get("agencyCommissionLastPB"));
}
you would have to implement a try/catch block
try {
element action
} catch (Exception e) {
//whatever you want to happen when it fails
}`
But I would ask myself why is the test not consistent with every run? Why should this step not pass every time?
One pattern you can use is:
try {}
catch {}
Place your offending code in the try block and any error code in the catch block.
If an exception is raised in the try, the catch block will be called instead of proceeding to the next line in the try

Handling Windows Store App exceptions from GetFileAsync

I have a problem with the following code example:
Windows::Storage::StorageFolder^ location = Package::Current->InstalledLocation;
try
{
task<StorageFile^> GetFileTask(location->GetFileAsync(sn));
GetFileTask.then([=](StorageFile^ file)
{
try
{
task<IBuffer^> ReadFileTask(FileIO::ReadBufferAsync(file));
ReadFileTask.then([=](IBuffer^ readBuffer)
{
// process file contents here
});
}
catch(Platform::Exception^ ex)
{
// Handle error here
}
});
}
catch(Platform::Exception^ ex)
{
// Handle error here
}
When using a filename that doesn't exist the function throws an exception:
Unhandled exception at 0x0FFCC531 (msvcr110d.dll) in GameTest2.exe: An invalid parameter was passed to a function that considers invalid parameters fatal.
I've been searching the internet and this exception breaks only when connected to the debugger. I'm using VS 2012. I've turned off all the relevant 'break on exception' but it still causes the debugger to break and non of my handlers are getting a chance to handle the exception.
If the file is missing I would expect the GetFileAsync method to throw a 'File doesn't exist' exception. Not sure why it keeps throwing the 'Invalid parameter' exception.
This is starting to bother me and I just can't find any known solution to this issue. Anyone have any ideas?
I'm going to try and change the method to not use the task<> code. Instead I'll call the GetFileAsync using 'await'. However I believe 'await' will just cause the calling thread to wait until the GetFileAsync has finished, which kind of defeats the point of asynchronous loading.
I'm wondering if this is a common issue with exception handling when using tasks.
Update:
OK, I've now found the solution:
task<StorageFile^>( location->GetFileAsync(sn)).then([](StorageFile^ openedFile)
{
return FileIO::ReadBufferAsync(openedFile);
}).then([](IBuffer^ readBuffer)
{
// Process file
}).then([](task<void> t)
{
try
{
t.get();
}
catch(Platform::Exception^ e)
{
// Handle error
}
});
It seems there needs to be an extra 'then' condition added to the end of the chain to pick up the exception.

Why, when I am testing that a method throws an exception and the method throw an exception, does the test stop?

I have a unit test that tests if method throws an exception when condition is present, and method does throws exception as expected.
- (void)testMethodThrowsWhenConditionIsPresent {
XCTAssertThrows([Foo methodWithCondition: condition], #"Condition is true, method should throw exception");
}
Here is the exception source:
- (void)methodWithCondition:(someType)condition {
if (condition) {
[NSException raise: #"condition is true!" format: #"condition is true!"];
}
}
Why does the test stop at the line the exception is thrown? The test does not go on, it stops at that line, when I expect it to continue and return 1 from XCTAssertThrows(), making the test succeed. The test instead stops with Xcode bringing me to the line it was thrown, with a green `Thread 1: breakpoint 1.1' and the debugger appearing in the console.
Why does the test stop when the execution is thrown?
Because you have a breakpoint, which stops execution.
Why, after removing the breakpoint, does my application crash when the exception is thrown?
Because you have an unhandled exception. Unhandled exceptions cause your program to crash.
How can I handle an exception so it won't crash my program?
The easy answer to this question is to simply NOT throw an exception. In other programming languages, like Java, this is perfectly standard. But in Objective-C, we don't really do exceptions. In Objective-C, exceptions should be saved for TRULY exceptional behavior.
With that said, and a strong suggestion for you to find another way to handle whatever it is you're trying to handle, this is how you handle an exception in Objective-C:
#try {
// code that could throw an exception
}
#catch (NSException *e) {
// handle the exception...
}
#finally {
// post try-catch code, executed every time
}

Handling exception in Javaparser

I am trying to handle the exception produced by Javaparser library due to token error. I used the following code.
String content=getTheSource();
ByteArrayInputStream bin=new ByteArrayInputStream(content.getBytes());
try
{
CompilationUnit cu=JavaParser.parse(bin);
} catch (Exception e) {
// TODO Auto-generated catch block
//e.printStackTrace();
//my handling code here
}finally{
bin.close();
}
However, the exception was never caught and I am getting a different exception generated from somewhere else. I got this exception:
Exception in thread "main" japa.parser.TokenMgrError: Lexical error at line 1, column 16. Encountered: "#" (35), after : ""
at japa.parser.ASTParserTokenManager.getNextToken(ASTParserTokenManager.java:2247)
at japa.parser.ASTParser.jj_ntk(ASTParser.java:9986)
at japa.parser.ASTParser.ClassOrInterfaceBody(ASTParser.java:926)
at japa.parser.ASTParser.ClassOrInterfaceDeclaration(ASTParser.java:604)
at japa.parser.ASTParser.TypeDeclaration(ASTParser.java:524)
at japa.parser.ASTParser.CompilationUnit(ASTParser.java:269)
at japa.parser.JavaParser.parse(JavaParser.java:81)
at japa.parser.JavaParser.parse(JavaParser.java:94)
at misc.CompileTest.main(CompileTest.java:45)
Any idea, how to handle the exception? Thanks in advance
As the name indicates, TokenMgrError is an error. So you have to catch an Error instead of Exception. If you want to catch both Error and Exception, you can use Throwable instead.
Originally, this error is throwed by JavaCC (TokenMgrError) which is used by Javaparser.
From version 3 on, JavaParser will/should not throw this error anymore.

WebKit how to handle an exception

Hey, I'm using a ScriptDebugDelegate to notify me when an exception occurs in the exceptionWasRaised function.
However, I'd like to know how I could ignore the exception, ie. just skip the line of code that'd normally fire an exception.
Thanks
ASH
If you know the line where the exception occurs you could use a try/catch with no code inside the catch block
#try {
//my code that throws exception
} #catch ( NSException *e ) {
}
You can even filter it by using a specific exception type that you want like for CustomException:
#try {
//my code that throws exception
} #catch ( MyCustomException *e ) {
}
What will cause any MyCustomException to be ignored, and all other to be fired.
NOTE: It is important to use that only for testing and debugging proposes as empty catches are always wrong.