确定不会触发异常时,如何优雅消除Java强制异常处理?
优雅消除
NoSuchAlgorithmException强制处理的几种方案 针对你明确知晓NativePRNGNonBlocking算法一定存在的场景,有以下几种优雅方式消除不必要的异常处理代码:
方案一:静态初始化块初始化SecureRandom
把SecureRandom的初始化放到静态块中,只会在类加载时执行一次,若真出现异常(虽你确定不会),会自动抛出ExceptionInInitializerError,无需手动捕获包装,同时还能避免重复创建实例:
import java.security.SecureRandom; public class Randomness { private static final String ALGORITHM = "NativePRNGNonBlocking"; private static final SecureRandom SECURE_RANDOM; static { SECURE_RANDOM = SecureRandom.getInstance(ALGORITHM); } public static byte[] createRandomBytes(int byteLength) { byte[] buffer = new byte[byteLength]; SECURE_RANDOM.nextBytes(buffer); return buffer; } }
方案二:用AssertionError包装异常(适合延迟初始化场景)
如果需要延迟初始化SecureRandom,可以将异常包装为AssertionError抛出——它比普通RuntimeException更贴切,代表程序逻辑上的断言失败(你认定算法存在,若抛出则说明假设不成立):
import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; public class Randomness { private static final String ALGORITHM = "NativePRNGNonBlocking"; private static SecureRandom getSecureRandom() { try { return SecureRandom.getInstance(ALGORITHM); } catch (NoSuchAlgorithmException e) { throw new AssertionError("NativePRNGNonBlocking算法不存在,与预期不符", e); } } public static byte[] createRandomBytes(int byteLength) { byte[] buffer = new byte[byteLength]; getSecureRandom().nextBytes(buffer); return buffer; } }
方案三:使用Java 11+的getInstanceStrong()(若适配需求)
如果你的场景允许使用系统默认强随机数算法,Java 11及以上提供的getInstanceStrong()方法无需指定算法名,自然不会抛出NoSuchAlgorithmException:
import java.security.SecureRandom; public class Randomness { private static final SecureRandom SECURE_RANDOM = SecureRandom.getInstanceStrong(); public static byte[] createRandomBytes(int byteLength) { byte[] buffer = new byte[byteLength]; SECURE_RANDOM.nextBytes(buffer); return buffer; } }
注意:此方法返回的算法不一定是NativePRNGNonBlocking,需根据实际需求选择。
内容的提问来源于stack exchange,提问作者DXW
相关产品推荐
相关产品推荐

