gpt4 book ai didi

java - 用 if 条件替换 try-catch block

转载 作者:行者123 更新时间:2023-12-02 04:19:56 25 4
gpt4 key购买 nike

出于代码质量原因,我想替换 try catch在我的代码中使用 if 进行阻止条件以避免使用 FrontendException .

这是我的代码:

Schema mySchema = new Schema();
mySchema.add(new Schema.FieldSchema("myInteger", DataType.INTEGER));
mySchema.add(new Schema.FieldSchema("myBoolean", DataType.BOOLEAN));
Schema tupleSchema = new Schema();
try {
tupleSchema.add(new Schema.FieldSchema("ARRAY_ELEM", mySchema, DataType.BAG));
} catch (FrontendException e) {
tupleSchema = new Schema(new Schema.FieldSchema(getSchemaName("myClass", input), DataType.DOUBLE));
}
return tupleSchema;

是否可以使用 if else 替换此代码健康)状况?这样我就不必使用这种类型的异常,这对 SonarQube 来说会更好。

有什么想法吗?

最佳答案

Schema.FieldSchema 构造函数抛出的异常是确定性的。这是构造函数的代码;

public FieldSchema(String a, Schema s, byte t)  throws FrontendException {
alias = a;
schema = s;
log.debug("t: " + t + " Bag: " + DataType.BAG + " tuple: " + DataType.TUPLE);

if ((null != s) && !(DataType.isSchemaType(t))) {
int errCode = 1020;
throw new FrontendException("Only a BAG, TUPLE or MAP can have schemas. Got "
+ DataType.findTypeName(t), errCode, PigException.INPUT);
}

type = t;
canonicalName = CanonicalNamer.getNewName();
}

因此,如果;则抛出异常;

  • 给定的架构为空
  • 给定的 DataType 不是架构类型

你提前知道是否会抛出异常。在您的情况下,情况并非如此,因此您可以安全地忽略异常,因为它永远不会被抛出。您可以删除 catch block 中的代码。您也可以将其替换为;

throw new IllegalStateException("Summon Cthulhu");

与获取 UTF-8 字符集类似;

String test = "abc";
byte[] bytes;
try {
bytes = test.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
//Can never happen although the compiler forces us to catch it
}

尽管如果不支持字符集,getBytes 方法可能会引发异常,但始终保证支持 UTF-8 字符集。

关于java - 用 if 条件替换 try-catch block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32904318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com