Throwable
以下三个对应实例
public class Demo_Error {
public static void main(String[] args) {
show();
}
public static void show(){
//循环调用,报错:StackOverFlowError,栈内存溢出!
show();
}
}
public class Demo_RuntimeException {
//throws FileNotFoundException 运行之前FileReader("D://a.txt");提示异常,引文文件未发现异常,必须抛出异常
public static void main(String[] args) throws FileNotFoundException{
FileReader fr = new FileReader("D://a.txt");//文件可能不存在
System.out.println(fr);
}
}
public class Demo_NoRunTimeException {
public static void main(String[] args) {
double a = 10/0;//控制台报:java.lang.ArithmeticException: / by zero
System.out.println(a);
}
}
//method --> main --> jvm --> 将异常出现的位置和错误的原因打印在控制台
public class Demo_Exception {
//throws FileNotFoundException 运行之前FileReader("D://a.txt");提示异常,引文文件可能不存在,必须抛出异常
public static void main(String[] args) throws FileNotFoundException {
FileReader fr = new FileReader("D://a.txt");
System.out.println(fr);
}
}
public class Demo1_Exception {
public static void main(String[] args) throws Exception {
Person p = new Person();
p.setAge(-23);
}
}
class Person{
private int age;
public int getAge(){
return age;
}
public void setAge(int age) throws Exception {
if (age >= 0 && age <= 200) {
this.age = age;
}else {
throw new Exception("您的年龄赋值有误,请检查!");
}
}
}
public class Demo2_Exception {
public static void main(String[] args) {
try {
int[] arr = null;//可能出现异常的代码
System.out.println(arr[0]);
} catch (Exception e) { //要抓捕的异常
//异常的处理方式
System.out.println("出错了!");
}
System.out.println("检查try/catch是否影响后续代码的执行?");
}
}
@Transactional(rollbackFor={Exception.class})
public class Demo1_Exception {
public static void main(String[] args){
Person p = new Person();
p.setAge(-23);
}
}
class Person{
private int age;
public int getAge(){
return age;
}
public void setAge(int age) {
if (age >= 0 && age <= 200) {
this.age = age;
}else {
throw new MyPersonAgeException("您的年龄赋值有误,请检查!");
}
}
}
//自定义异常类
class MyPersonAgeException extends RuntimeException{
public MyPersonAgeException() {
}
public MyPersonAgeException(String message) {
super(message);
}
}
本文由 Alicyu 创作,如果您觉得本文不错,请随意赞赏
采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
原文链接:https://www.alicyu.com/archives/exception
最后更新:2019-10-18 15:04:44
Update your browser to view this website correctly. Update my browser now