【Java笔记】包的定义及使用、设计模式(重要)(单例模式、多例模式)、异常与捕获 - 总结六

面向对象开发

备注:

链接:

1.设计模式  链接1:

https://blog.csdn.net/qq_43109561/article/details/88788005

范例:

1.异常处理格式的语法  范例1:

try{
有可能出现异常的语句 ;
}[catch (异常类 对象) {
} ... ]
[finally {
异常的出口
}]

2.调用异常类中提供的printStackTrace()方法进行完整异常信息的输出   范例2:

package test;

public class Test {
	public static void main(String[] args) {
		System.out.println("1.数学计算开始前");
		try {
			System.out.println("2.进行数学计算:"+10/0);
		} catch (ArithmeticException e) {
			e.printStackTrace();
		}
		System.out.println("3.数学计算结束后");
	}
}

3.调用throws声明的方法,在调用时必须明确的使用try..catch..进行捕获   范例3:

package test;
public class Test {
	public static void main(String[] args) {
		try {
			System.out.println(calculate(10, 0));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static int calculate(int x,int y) throws Exception {
		return x/y ;
	}
}

4.thorw直接编写在语句之中,表示人为进行异常的抛出  范例4:

public static void main(String[] args){
	try {
		throw new Exception("抛个异常玩玩") ;
	} catch (Exception e) {
		e.printStackTrace();
	}
}

5.异常处理标准格式  范例5

public class TestException{
	public static void main(String[] args){
		try{
			calculate(10,0);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	public static int calculate(int x,int y )throws Exception{
		int result = 0;
		System.out.println("1.计算前");
		try{
			result = x / y;
		}catch(Exception e){
			throw e;
		}finally{
			System.out.println("2.计算结束");
		}
		return result;
	}
}

或者直接简化为try..finally:

public class TestException{
	public static void main(String[] args){
		try{
			calculate(10,0);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	public static int calculate(int x,int y )throws Exception{
		int result = 0;
		System.out.println("1.计算前");
		try{
			result = x / y;
		}finally{
			System.out.println("2.计算结束");
		}
		return result;
	}
}

6.自定义的异常类    范例6:

package test;

class AddException extends Exception {
	public AddException(String msg) {
		super(msg) ;
	}
}
public class Test {
	public static void main(String[] args) throws Exception{
		int num1 = 20 ;
		int num2 = 30 ;
		if (num1+num2==50) {
			throw new AddException("错误的相加操作") ;
		}
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值