java创建一个自定义异常类,并在一个方法中抛出自定义异常,在该方法的catch处理程序中捕获并重新抛出
6个回答
展开全部
public void MyException(String name){
if(null==name || "".equals(name)){
throw new RuntimeException("姓名的格式不正确");
}
}
public static void main(String[] args) {
try {
new aaa().MyException("");
} catch (RuntimeException e) {
System.out.println(e.getMessage());
}
}
展开全部
首先自定义一个异常类
public class ActionException extends Exception{
public String returnMessage;
public ActionException(String returnMessage){
this.returnMessage = returnMessage;
}
public String getReturnMessage(){
return this.returnMessage;
}
代码中如果用到这个自定义的异常类,这里的代码只是做了个演示
private void validate(int a,int b)throws ActionException{
if(a>b){
throw new ActionException("a > b");
}
if(a<b){
throw new ActionException("a < b");
}
}
业务逻辑代码中
public String process(){
try{
validate(a,b);
}catch(ActionException ae){
System.out.println(ae.getReturnMessage());
}
}
public class ActionException extends Exception{
public String returnMessage;
public ActionException(String returnMessage){
this.returnMessage = returnMessage;
}
public String getReturnMessage(){
return this.returnMessage;
}
代码中如果用到这个自定义的异常类,这里的代码只是做了个演示
private void validate(int a,int b)throws ActionException{
if(a>b){
throw new ActionException("a > b");
}
if(a<b){
throw new ActionException("a < b");
}
}
业务逻辑代码中
public String process(){
try{
validate(a,b);
}catch(ActionException ae){
System.out.println(ae.getReturnMessage());
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
public class sssss {
public static void main(String[] args) {
System.out.print("Please input an Integer: ");
int value = new Scanner(System.in).nextInt();
try{
if(value < 0){
throw new MyException("My Exception comes!");
}
}catch (MyException myExp){
System.out.println("MyExcepton caugth!");
}
}
}
class MyException extends Exception{
public MyException(String s){
System.out.println("MyException occurs. The value must be greater than ZERO!");
}
}
-----------------------
Please input an Integer: -5
MyException occurs. The value must be greater than ZERO!
MyExcepton caugth!
public static void main(String[] args) {
System.out.print("Please input an Integer: ");
int value = new Scanner(System.in).nextInt();
try{
if(value < 0){
throw new MyException("My Exception comes!");
}
}catch (MyException myExp){
System.out.println("MyExcepton caugth!");
}
}
}
class MyException extends Exception{
public MyException(String s){
System.out.println("MyException occurs. The value must be greater than ZERO!");
}
}
-----------------------
Please input an Integer: -5
MyException occurs. The value must be greater than ZERO!
MyExcepton caugth!
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
所以你想问什么?怎么定义这个类?
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
楼上正解。很好很强大
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询