Java中的检查异常与未检查异常

异常是一种不需要的或意外的事件,发生在程序执行期间,即运行时,它会中断程序指令的正常流动。在Java中,有两种类型的异常:

null
  1. 检查异常
  2. 未经检查的例外情况

图片[1]-Java中的检查异常与未检查异常-yiteyi-C++库

检查违例

这些 是编译时检查的异常。如果某个方法中的某些代码抛出选中的异常,那么该方法必须处理该异常,或者必须使用 投掷 关键词 .

例如,考虑下面的java程序,它在“C:ESTA。TXT”位置打开文件并打印它的前三行。程序不会编译,因为函数main()使用FileReader(),FileReader()抛出一个选中的异常 FileNotFoundException 。它还使用readLine()和close()方法,这些方法还抛出checked exception IOException

例子:

JAVA

// Java Program to Illustrate Checked Exceptions
// Where FileNotFoundException occured
// Importing I/O classes
import java.io.*;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Reading file from path in local directory
FileReader file = new FileReader( "C:\test\a.txt" );
// Creating object as one of ways of taking input
BufferedReader fileInput = new BufferedReader(file);
// Printing first 3 lines of file "C: esta.txt"
for ( int counter = 0 ; counter < 3 ; counter++)
System.out.println(fileInput.readLine());
// Closing file connections
// using close() method
fileInput.close();
}
}


输出:

图片[2]-Java中的检查异常与未检查异常-yiteyi-C++库

要修复上述程序,我们要么需要使用throws指定异常列表,要么需要使用try-catch块。我们在下面的程序中使用了投掷。自从 FileNotFoundException IOException ,我们可以指定 IOException 在抛出列表中,并使上述程序编译器无错误。

例子:

JAVA

// Java Program to Illustrate Checked Exceptions
// Where FileNotFoundException does not occur
// Importing I/O classes
import java.io.*;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
throws IOException
{
// Creating a file and reading from local repository
FileReader file = new FileReader( "C:\test\a.txt" );
// Reading content inside a file
BufferedReader fileInput = new BufferedReader(file);
// Printing first 3 lines of file "C: esta.txt"
for ( int counter = 0 ; counter < 3 ; counter++)
System.out.println(fileInput.readLine());
// Closing all file connections
// using close() method
// Good practice to avoid any memory leakage
fileInput.close();
}
}


输出:

First three lines of file "C:	esta.txt"

不检查违例

这些是编译时未检查的异常。在C++中,所有异常都是未选中的,因此编译器不强制处理或指定异常。这取决于程序员是否文明,是否指定或捕获异常。Java中的异常 错误 运行期异常 类是未检查的异常,其他所有在throwable下的都被检查。

考虑下面的java程序。它编译得很好,但会抛出 算术异常 跑步的时候。编译器允许它编译,因为 算术异常 是一个未经检查的例外。

例子:

JAVA

// Java Program to Illustrate Un-checked Exceptions
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Here we are dividing by 0
// which will not be caught at compile time
// as there is no mistake but caught at runtime
// because it is mathematically incorrect
int x = 0 ;
int y = 10 ;
int z = y / x;
}
}


输出:

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at Main.main(Main.java:5)
Java Result: 1

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享