相当于try ... catch作为表达式

问题描述

我正在寻找一种类似的方法

myVar = try {someFunction();} catch (e) {return undefined;} ?? defaultValue;

我知道这是不正确的,但是您明白了。我只是想知道是否有一种优雅的方法

解决方法

您目前可以做的最好的事情可能是IIFE:

        final ArrayList<String> arrPackage;
        String nameS = name.getText().toString().trim();
        String birhtdayS = birthday.getText().toString().trim();
        String gendarS = gendar.getText().toString().trim();
        String phoneS = phone.getText().toString().trim();
        arrPackage.add(nameS);
        arrPackage.add(birhtdayS);
        arrPackage.add(gendarS);
        arrPackage.add(phoneS);
        Gson gson = new Gson();
        String json = gson.toJson(arrPackage);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("Set",json );
        editor.commit();
     }
  
,

实施例如afterThrowing method modifier可能会导致表达式与OP的伪代码一样短……

DatabaseReference mMovieRef = FirebaseDatabase.getInstance().getReferenceFromUrl("xxxxxxxxxxxxxxxxxxxxxx");
mRef.child("Name");

...然后会变成类似...

const value = try {someFunction();} catch (e) {return undefined;} ?? defaultValue;

...实现和示例代码作为概念证明...

const value = (someFunction.afterThrowing(() => null)()) ?? defaultValue;
// myVar = try {someFunction();} catch (e) {return undefined;} ?? defaultValue;

function throwError() {
  throw (new Error('invocation failure'));
}
function getDate() {
  return Date.now();
}
const defaultValue = '... did throw.'

// expressions as short and as close as one can get
// to what has been ask for ...
//
console.log(
  (getDate.afterThrowing(() => null)()) ?? defaultValue
);
console.log(
  (throwError.afterThrowing(() => null)()) ?? defaultValue
);


// demonstrate capability of the after throwing handler ...
function afterThrowingHandler(error,args) {
  console.log(
    'afterThrowingHandler :: context,error,argsList :',this,error.toString(),Array.from(args)
  );
  return null; // according to the OP's use case.
}

console.log(
  (getDate.afterThrowing(afterThrowingHandler)()) ?? defaultValue
);

console.log(
  (throwError.afterThrowing(

    afterThrowingHandler,{ biz: 'buzz' }

  )('foo','bar','baz')) ?? defaultValue
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

我不介意有一天JavaScript正式启用... <script> (function (Function) { const fctPrototype = Function.prototype; const FUNCTION_TYPE = (typeof Function); function isFunction(type) { return ( (typeof type == FUNCTION_TYPE) && (typeof type.call == FUNCTION_TYPE) && (typeof type.apply == FUNCTION_TYPE) ); } function getSanitizedTarget(target) { return ((target != null) && target) || null; } function afterThrowing/*Modifier*/(handler,target) { target = getSanitizedTarget(target); const proceed = this; return ( isFunction(handler) && isFunction(proceed) && function () { const context = target || getSanitizedTarget(this); const args = arguments; let result; try { result = proceed.apply(context,args); } catch (exception) { result = handler.call(context,exception,args); } return result; } ) || proceed; } // afterThrowing.toString = () => 'afterThrowing() { [native code] }'; Object.defineProperty(fctPrototype,'afterThrowing',{ configurable: true,writable: true,value: afterThrowing/*Modifier*/ }); }(Function)); </script> before Function.prototype[ after | around | afterThrowing | afterFinally |

,

功能性尝试

const tryF = (func) => {
  try {
    return func();
  } catch (e) {
    return null;
  }
};

然后使用

Const val = tryF(() => dosomething ())