{"id":21089205,"url":"https://github.com/luo-zhan/lambdaexceptionthrower","last_synced_at":"2025-05-16T11:32:53.618Z","repository":{"id":59907050,"uuid":"214820419","full_name":"luo-zhan/LambdaExceptionThrower","owner":"luo-zhan","description":"写Lambda表达式不想要捕获异常怎么办，试试这个！","archived":false,"fork":false,"pushed_at":"2023-07-21T08:58:20.000Z","size":36,"stargazers_count":13,"open_issues_count":0,"forks_count":4,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-04T01:11:21.092Z","etag":null,"topics":["exception-handler","java8","lambda"],"latest_commit_sha":null,"homepage":null,"language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/luo-zhan.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-10-13T12:58:13.000Z","updated_at":"2024-07-09T09:42:20.000Z","dependencies_parsed_at":"2022-09-25T06:50:14.639Z","dependency_job_id":null,"html_url":"https://github.com/luo-zhan/LambdaExceptionThrower","commit_stats":null,"previous_names":["luo-zhan/lambdaexceptionthrower"],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/luo-zhan%2FLambdaExceptionThrower","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/luo-zhan%2FLambdaExceptionThrower/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/luo-zhan%2FLambdaExceptionThrower/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/luo-zhan%2FLambdaExceptionThrower/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/luo-zhan","download_url":"https://codeload.github.com/luo-zhan/LambdaExceptionThrower/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254522525,"owners_count":22085143,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["exception-handler","java8","lambda"],"created_at":"2024-11-19T21:24:21.299Z","updated_at":"2025-05-16T11:32:50.457Z","avatar_url":"https://github.com/luo-zhan.png","language":"Java","readme":"# LambdaExceptionThrower\n\n[![GitHub](https://img.shields.io/github/license/luo-zhan/Transformer)](http://opensource.org/licenses/apache-2-0)\n[![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/luo-zhan/LambdaExceptionThrower)]()\n[![SolarLint](https://img.shields.io/badge/SolarLint-Perfect-gold)]()\n[![GitHub last commit](https://img.shields.io/github/last-commit/luo-zhan/LambdaExceptionThrower?label=Last%20commit)]()\n\nJava里写Lambda表达式的时候居然必须要try-catch掉内部异常，简直不能忍！😠\n\n## 使用说明\n\n### 1. lambda方法声明\n\n```java\n// 编译不通过，未处理异常“MalformedURLException”\nFunction\u003cString, URL\u003e function=URL::new;\n// 使用LambdaExceptionThrower后，编译通过！\n        Function\u003cString, URL\u003e function=wrapFunction(URL::new);\n```\n### 2. 看一个更常见的例子\n\n如果我们在`Stream`的`map()`方法中使用一个会抛出异常的方法：（此处将一批url字符串转换成URL对象模拟这种场景）\n\n#### Before：\n\n```java\nclass Test {\n\n    public static void main(String[] args) {\n        List\u003cString\u003e source = Arrays.asList(\"http://example1.com\", \"http://example2.com\", \"http://example3.com\");\n        List\u003cURL\u003e urlList = source.stream().map(url -\u003e {\n            // 必须要捕获异常，否则无法编译通过\n            try {\n                return new URL(url);\n            } catch (MalformedURLException e) {\n                // 抛异常只能抛unchecked-exception(RuntimeException或Error)，或者处理掉异常不往上抛。\n                throw new RuntimeException(e);\n            }\n        }).collect(Collectors.toList());\n    }\n}\n```\n上面代码中`new URL(url)`会抛出`MalformedURLException`，在lambda表达式中必须被try-catch，无法向上抛出，这样不仅代码累赘，而且在实际开发中，绝大多数的异常都是需要向上抛出的，这样就无法简便的使用Stream API了。\n\n#### After\n\n```java\n// 此处静态导入方法\n\nimport static com.robot.util.LambdaExceptionUtil.wrapFunction;\n\nclass Test {\n    public static void main(String[] args) throws MalformedURLException { // 注意这里增加了异常申明\n        List\u003cString\u003e source = Arrays.asList(\"http://example1.com\", \"http://example2.com\", \"http://example3.com\");\n\n        // 只需要在原来的lambda表达式外用wrapFunction()方法包裹一下即可，注意异常已经被抛到了上层\n        List\u003cURL\u003e urlList = source.stream()\n                .map(wrapFunction(url -\u003e new URL(url)))\n                .collect(Collectors.toList());\n\n        // 还可以使用方法引入，代码更加简洁！\n        List\u003cURL\u003e urlList1 = source.stream()\n                .map(wrapFunction(URL::new))\n                .collect(Collectors.toList());\n    }\n}\n```\n\n#### Tips\n\n1.使用IDEA写代码时可以直接敲`wrapFunction(...)`，然后按`⌥+↩︎`(`Opition+回车`，Windows是`Alt+回车`)，选择弹出菜单中的“import\nstatic...”即可快速导入方法\n![快捷静态导入](https://msb-edu-dev.oss-cn-beijing.aliyuncs.com/course/lambda2.png)\n\n2.使用`wrapFunction`方法包裹后，idea是会提示未捕获方法异常的，只需要点击一下就自动在方法上申明了异常，和平时写代码异常处理操作无异\n![快捷申明异常](https://msb-edu-dev.oss-cn-beijing.aliyuncs.com/course/lambda.png)\n\n## One more thing\n\n工具类中还提供了另一个很好用的方法，`sure()`。\n\n如果一段代码**确保**不会抛出所申明的异常，可以使用该方法进行包装，此时既不用写try-catch，也不用在方法申明上throw异常，代码相当简洁。\n\n```java\nimport static com.robot.util.LambdaExceptionUtil.sure;\n\nclass Test {\n    // 如下String的构造方法申明了UnsupportedEncodingException，但编码\"UTF-8\"是必定不会抛异常的，使用sure(...)进行包装\n    String text = sure(() -\u003e new String(byteArr, \"UTF-8\"));\n\n    // 通过class创建对象，而已知此实例化一定不会产生异常\n    Map map = sure(HashMap.class::newInstance);\n\n    // 反射获取某个类的属性，而已知这个类必然含有该属性\n    Field field = sure(() -\u003e someClass.getDeclaredField(\"id\"));\n\n    // 测试时用的sleep方法，不必改变测试方法上的异常申明\n    sure(() -\u003eThread.sleep(1000));\n}\n```\n\n\u003e 注意：sure方法虽然好用，但它也隐藏了可能的异常申明，所以请谨慎使用，确定(sure)一定不会抛出异常！\n\n## API\n\n有手就会😉\n\n```js\n// 最常用的4个\nwrapFunction(Function);// Function：普通函数（入参出参各一个）\nwrapConsumer(Consumer);// Consumer：消费函数（一个入参，没有出参）\nwrapSupplier(Supplier);// Supplier：提供函数（没有入参，一个出参）\nwrapPredicate(Predicate);// Predicate：条件函数（一个入参，一个出参，且出参类型是boolean）\n\n// 更多，和jdk8中的函数式接口一一对应\nwrapBiFunction(BiFunction);\nwrapBiConsumer(BiConsumer);\nwrapBiPredicate(BiPredicate);\nwrapRunnable(Runnable);\n\n// 确保不抛出异常时使用\nsure(Runnable);\nsure(Supplier);\n\n```\n\n## Note\n\n本工具实现方式是利用泛型的不确定性使得编译器无法区分抛出的异常是uncheck-exception还是check-exception，利用这个漏洞绕开了编译器的检查，所以不会编译报错，然后将异常抛到外层（此时异常还是原来的异常），这和很多解决方案中的把异常转换成RuntimeException抛出的原理是不同的，有兴趣的朋友可以参看源码。\n\n思路源自[@MarcG](https://stackoverflow.com/users/3411681/marcg)\n与[@PaoloC](https://stackoverflow.com/users/2365724/paoloc)，感谢两位大神。\n\n如果发现问题或建议请提[Issues](https://github.com/Robot-L/LambdaExceptionThrower/issues)\n，如果对你有帮助，请点个Star，非常感谢~ ^_^\n\n扩展阅读：\n\n- [Java 8 Lambda function that throws exception?](https://stackoverflow.com/questions/18198176/java-8-lambda-function-that-throws-exception)\n- [How can I throw CHECKED exceptions from inside Java 8 streams?](https://stackoverflow.com/questions/27644361/how-can-i-throw-checked-exceptions-from-inside-java-8-streams)\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fluo-zhan%2Flambdaexceptionthrower","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fluo-zhan%2Flambdaexceptionthrower","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fluo-zhan%2Flambdaexceptionthrower/lists"}