Java 自定义异常:详细指南及代码示例
"Java 自定义异常:详细指南及代码示例"\n\n在 Java 中,您可以通过继承 Exception 类或 RuntimeException 类来自定义异常。\n\n继承 Exception 类的自定义异常是受检异常,需要在方法签名中声明或捕获处理。例如:\n\njava\npublic class CustomException extends Exception {\n public CustomException(String message) {\n super(message);\n }\n}\n\n\n继承 RuntimeException 类的自定义异常是非受检异常,不需要在方法签名中声明或捕获处理。例如:\n\njava\npublic class CustomRuntimeException extends RuntimeException {\n public CustomRuntimeException(String message) {\n super(message);\n }\n}\n\n\n在使用自定义异常时,可以使用 throw 关键字抛出异常,或者使用 try-catch 语句来捕获并处理异常。例如:\n\njava\npublic void process() throws CustomException {\n if (somethingIsWrong) {\n throw new CustomException(\"Something is wrong.\");\n }\n}\n\n\njava\npublic void process() {\n try {\n // some code\n if (somethingIsWrong) {\n throw new CustomException(\"Something is wrong.\");\n }\n // some code\n } catch (CustomException e) {\n System.out.println(e.getMessage());\n }\n}\n\n\n需要注意的是,在捕获自定义异常时,可以根据需要使用多个 catch 语句来捕获不同类型的异常,并分别进行处理。
原文地址: https://www.cveoy.top/t/topic/pZTJ 著作权归作者所有。请勿转载和采集!