Java异常机制##
捕获异常
(1)catch
(2)finally
(3)catch-finally
声明异常
(1)throws(Expection类型 Checked Exception类型)
(2)try-catch-finally
throw&throws
(1)throws用于声明方法可能产生的异常类型
(2)throw手动抛出异常对象
(3)throws写在方法名称后面
(4)throw写在方法里
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
try {
System.out.println("输入被除数");
int numA=input.nextInt();
System.out.println("输入除数");
int numB=input.nextInt();
int result= numA/numB;
System.out.println(numA+"/"+numB+"="+result);
}
/*异常一号catch(Exception e) {
e.printStackTrace();
}*/
/*异常二号finally {
System.out.println("......");
}*/
catch(ArithmeticException e) {
System.err.println(",,,,,");
System.out.println(" "+e.getMessage());
return ;
}finally {
System.out.println("finally中的代码");
}
}
}
自定义异常
public class CustomException extends Exception {
public CustomException() {
super();
// TODO Auto-generated constructor stub
}
public CustomException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
}
import java.util.Scanner;
public class testCustomException {
public static void main(String [] args) throws CustomException {
Scanner input=new Scanner(System.in);
System.out.println("请输入性别");
String gender=input.next();
if("男".equals(gender)||"女".equals(gender)) {
System.out.println("正确");
}else {
throw new CustomException("错误");
}
}
}