package YiChang;
public class Demo1 {
public static void main(String[] args) {
int divisor = 10;
int dividend = 110;
try { //试着执行代码块内容
System.out.println(divisor / dividend); // 10除以110 ArithmeticException 算数异常
}catch (Exception e){ // 捕获异常
e.printStackTrace();
System.out.println("程序捕获到了对应的异常");
}finally {
System.out.println("不管有没有出错,都会执行");
}
System.out.println(divisor/dividend);
System.out.println("啦啦啦,我是后续的内容");
System.out.println("啦啦啦,我是后续的内容");
}
}
package YiChang;
public class Demo2 {
public static void main(String[] args) {
int [ ] a = new int[3];
a[0] = (char)'1' ;
a[1] = 0;
a[2] = 1;
try {
System.out.println(a[0] / a[1] );
}catch (NumberFormatException e ){
System.out.println("数字格式异常");
}catch (ArithmeticException e ) {
System.out.println("数字格式化或者算数异常");
}
}
}
package YiChang;
public class Demo3 {
public static void main(String[] args) {
}
// 可以单独声明异常 抛出异常的同时,必须声名异常
public void setSex(String sex) throws Exception{ // 声明有可能有异常
if ( (sex.equals("男") || sex.equals("女")) ){
throw new Exception("性别既不是男又不是女");
}
}
}
package YiChang;
/*
1.需要继承自Exception
2.需要复写无参构造方法
3.需要复写message参数的构造方法
*/
public class SexException extends Exception{
public SexException(){
}
public SexException(String message) {
super(message);
System.out.println("性别异常");
}
}