Is there an opposite of catch? - javascript

By running the following, you can run code if an error is thrown.
try {
// test
} catch (e) {
// error output
}
Is there a similar way to run code only if no error is thrown?

Sure there is, see the comment inline.
try {
// test
// No error is thrown if program control reaches here
} catch {
// error output
}
Consider using an additional try block in the "No error is thrown" part if you don't want the outer catch to handle any other errors.

Related

How to throw an exception with indent?

Is there any way to throw javascript errors and force it to be indented?
Instead of 'Error' to be ' Error'. If not, what can I use instead, that will surely exit my node.js process. Thanks.
You can't modify the way node displays an uncaught error. But, you can catch the error and choose to display it however you want, before exiting your program.
class SpecialError extends Error {}
function main() {
// ...
throw new SpecialError('Whoops!')
}
// This is at the very end, so when the catch finishes,
// there's nothing left to execute, and the program ends.
try {
main()
} catch (err) {
if (!(err instanceof SpecialError)) throw err
console.error([
` Error: ${err.message}`, // Lots of indentation
...err.stack.split('\n').slice(1)
].join('\n'))
// Makes the program exit with status code 1. See here: https://nodejs.org/api/process.html#process_process_exitcode
// Uncomment this when you're in node.
// process.exitCode = 1;
}
I don't know if I realy understood your question, but did you try something like this?
throw new Error('\tSome error message.');

JSON.parse, already in try/catch block, still throws syntax error

parseJsonMsg(msg, jsonCallBack) {
try {
let content = JSON.parse(msg.content);
jsonCallBack(null, content);
} catch (err) {
console.log('[MSG processing ERROR]: ', err.message);
jsonCallBack(err);
}
}
This code is used to log the error whenever it is unable to parse a message.
Apart from logging, this throws syntax error if unable to parse. Why is that so? How can it be handled?
Any advice would be great
I suspect it is the method you are passing in as a parameter that is throwing the error. Make sure jsonCallBack does its own error handling. What is the error you receive?
Errors can be thrown anywhere, including inside catch blocks. If an error is thrown in a catch block it will percolate up the stack until it is either caught or the stack is exhausted and it becomes an uncaught exception.
bit of rewrite
parseJsonMsg(msg, jsonCallBack) {
var err;
var content;
try {
content = JSON.parse(msg.content);
} catch (ex) {
console.log('[MSG processing ERROR]: ', err.message);
err = ex;
}
jsonCallBack(err, content);
}
then as said above, the parse error is forwarded to the caller in jsonCallBack(err)
So it may be the caller which throws the error.
To fix your problem, you should not comment that call jsonCallBack(err) but, depending on the type of caller, bind its error handler then decide what to do.

Try-Catch not working in TestComplete

In test complete I am trying to use a try-catch block to see if a message box has an okay button and then click the okay button without crashing. I put the click operation inside a try block so if it fails the catch block can deal with the error, but it is crashing inside the try block. Here's an example:
try
{
okayButton = SomeLocation;
okayButton.click();
}
catch(err)
{
do something;
}
I would think that when Test Complete can't click the okay button, it would move into the catch block. However, I get an error on the okayButton.click(); line, which stops the test run. It says "there was an attempt to preform an action on a zero-sized window.". Does anyone know how do deal with this? Thanks in advance.
If okayButton.click(); does not throw an err, Your catch block will never be executed. You should validate that when okayButton.click(); fails, it throws the error your catch block is expecting.
It may be that okayButton.click(); is returning the error instead of throwing it.

Testing URL schemes with try/catch

I'm trying to test URL schemes via javascript try/catch blocks but my catch blocks are not being executed. Safari just skips them entirely and I don't understand why?!
function open_twitter() {
if (!IS_IOS){ //made unequal IOS so that I could test it on my Macbook
try {
window.location = "twitter://"; //fails and should go to the catch block
} catch (e) { //skipped
try { //skipped
window.location = TWITTERRIFIC_URL_SCHEME; //skipped
} catch (e) { //skipped
null; //skipped
} //skipped
} //skipped
} else {
window.open(TWITTER_URL, "_blank");
}
}
Does anyone have an idea why this is happening?
I want the code to test the first URL scheme. If that isn't successful than it should (in theory) go to the catch block and run the code inside which is in my case a try block again with the next URL scheme to test and so on and so forth.
But this doesn't happen?! I'm really confused...
Try catch doesn't work exactly like what you wrote, You'll need to provide your catch with an exception, Else it doesn't know something bad happened.
See these docs : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
try/catch should be used as a simple test with your custom exception. For example,
try
{
if(false==false)
{
throw "myException"; // generates an exception
}
catch (e) {
// statements to handle any exceptions
logMyErrors(e); // pass exception object to error handler
}
As you can see, The try should test for something and return an exception if some condition is met.

How javascript try...catch statement works

I am trying to test in browsermob if certain input field work or not. I am attempting to use a try...catch statement which I have never used before. I know that the form is:
try {
//some code
} catch (){
//some error code
};
What exactly is supposed to be put in the parenthesis after the catch statement?
When I try to use the statement it runs everything through the catch statement no matter if it is not an error. What am I doing wrong?
See the “try...catch statement” guide on MDN.
In short, try/catch is used to handle exceptions (which are "thrown" using the throw statement). The syntax for try/catch is:
try {
// Code
} catch (varName) { // Optional
// If exception thrown in try block,
// execute this block
} finally { // Optional
// Execute this block after
// try or after catch clause
// (i.e. this is *always* called)
}
varName is available to the scope of the catch block only. It refers to the exception object which was thrown (which could be any type of object, e.g. a String, but is usually an Error object).
The try catch statement is used to detected for exceptions/errors that are raised inside the try-block. In the catch block you can then react on this exceptional behavior and try to resolve it or get to a safe state.
You got the statement almost right:
try {
// code that may fail with error/exception
} catch (e) { // e represents the exception/error object
// react
}
Consider the following examples:
try {
var x = parseInt("xxx");
if(isNaN(x)){
throw new Error("Not a number");
}
} catch (e) { // e represents the exception/error object
alert(e);
}
try {
// some code
if(!condition){
throw new Error("Something went wrong!");
}
} catch (e) { // e represents the exception/error object
alert(e);
}
the stuff inside try {...} is what you want to execute. The stuff in catch() { ... } is what you want to execute if you get any javascript errors from anything executed in the try {...}
catch {...} only executes if there is a javascript error in the try {...} block. You can find out what the error is by doing for example this:
try {
// do something
} catch (err) {
alert(err);
}
According to ECMAScript specifications,
try {
// Code
} catch (varName) { // optional if 'finally' block is present.
if (condition) { // eg. (varName instanceof URIError)
// Condition (Type) specific error handling
}
else {
// Generic error handling
}
} finally { // Optional if 'catch' block is present.
// Execute this block after
// try or after catch clause
// (i.e. this is *always* called)
}
the code that is likely to throw an exception goes into try { }, The code to be run when an exception is thrown, comes into catch() { }. In catch() you can specify which exceptions you want to catch, and in which automatic variables to put it.
finally { } is always run, regardless whether exception was thrown or not.

Categories

Resources