• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

非常全面的Java异常处理(全文干货,值得收藏)

java 搞代码 4年前 (2022-01-09) 24次浏览 已收录 0个评论
文章目录[隐藏]

一.初始Java异常

1、对异常的理解:异常:在Java语言中,将程序执行中发生的不正常情况称为“异常”。(开发过程中的语法错误和逻辑错误不是异常)

2、Java程序在执行过程中所发生对异常事件可分为两类:

  •  Error:Java虚拟机无法解决的严重问题。如:JVM系统内部错误、资源耗尽等严重情况。比如:StackOverflowError和OOM。一般不编写针对性 的代码进行处理。
  • Exception: 其它因编程错误或偶然的外在因素导致的一般性问题,可以使用针对性的代码进行处理。例如:
  • 空指针访问
  • 试图读取不存在的文件
  • 网络连接中断
  • 数组角标越界

3、运行时异常和编译时异常

运行时异常

  • 是指编译器不要求强制处置的异常。一般是指编程时的逻辑错误,是程序员应该积极避免其出现的异常。java.lang.RuntimeException类及它的子类都是运行时异常。
  • 对于这类异常,可以不作处理,因为这类异常很普遍,若全处理可能会对程序的可读性和运行效率产生影响。

编译时异常

  • 是指编译器要求必须处置的异常。即程序在运行时由于外界因素造成的一 般性异常。编译器要求Java程序必须捕获或声明所有编译时异常。
  • 对于这类异常,如果程序不处理,可能会带来意想不到的结果。

二.Error和Exception

1.Error

代码示例一:java.lang.OutOfMemoryError(堆溢出)

public class ErrorTest {
 public static void main(String[] args) {
 //堆溢出:java.lang.OutOfMemoryError
 Long[] arr = new Long[1024*1024*1024];
 }
}

运行结果:

代码示例二:java.lang.StackOverflowError(栈溢出)

public class ErrorTest {
 public static void main(String[] args) {

 //栈溢出:java.lang.StackOverflowError
 main(args);
 }
}

运行结果:

2.Exception(运行时异常和编译时异常)

运行时异常

 /* ******************以下是运行时异常*****************<i>本文来源gaodai$ma#com搞$代*码网2</i>* */
 //ArithmeticException
 @Test
 public void test1(){
 int num1 = 3;
 int num2 = 0;
 int num3 = 3 / 0;
 }

 //InputMismatchException
 @Test
 public void test2(){
 Scanner scanner = new Scanner(System.in);
 int i = scanner.nextInt();
 System.out.println(i);
 scanner.close();
 }

 //NumberFormatException
 @Test
 public void test3(){
 String str = "abcd";
 int num = Integer.parseInt(str);
 }

 //ClassCastException
 @Test
 public void test4(){
 Object obj = new Boolean(true);
 String str = (String)obj;
 }

 //IndexOutOfBoundsException
 @Test
 public void test5(){
 ArrayIndexOutOfBoundsException
 Byte[] bytes = new Byte[3];
 System.out.println(bytes[4]);
 }

 //NullPointerException
 @Test
 public void test6(){
 int[] arr = null;
 System.out.println(arr[1]);
 }

编译时异常

/* ******************以下是编译时异常****************** */
 @Test
 public void test7(){
 File file = new File("a.txt");
 //java.io.FileNotFoundException
 FileInputStream fis = new FileInputStream(file);
 //java.io.IOException
 int date = fis.read();
 while (date != -1){
  System.out.println((char)date);
  date = fis.read();
 }

 fis.close();
 }

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:非常全面的Java异常处理(全文干货,值得收藏)

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址