【Java笔记】包的定义及使用、设计模式(重要)(单例模式、多例模式)、异常与捕获 - 总结六
面向对象开发
备注:
链接:
1.设计模式 链接1:
https://blog.****.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("错误的相加操作") ;
}
}
}