Java中的错误与异常

在java中,错误和异常都是java的子类。lang.一次性课程。 错误 指用户进行的导致程序运行异常的非法操作。在编译或执行程序之前,编程错误通常不会被发现。有些错误会阻止程序被编译或执行。因此,在编译和执行之前,应该删除错误。它有三种类型:

null
  • 编译时
  • 运行时间
  • 必然的

鉴于 java中的异常 指在程序执行期间,即在运行时发生的一种不希望发生的或意外的事件,它会中断程序指令的正常流动。

图片[1]-Java中的错误与异常-yiteyi-C++库

现在让我们讨论各种类型的错误,以便更好地理解数组。正如标题中所讨论的,一个错误表示一个合理的应用程序不应该试图捕捉的严重问题。错误是任何处理技术都无法恢复的情况。它肯定会导致程序异常终止。错误属于未检查类型,大多数发生在运行时。一些错误的例子是内存不足错误或系统崩溃错误。

例1 编译时错误

JAVA

// Java Program to Illustrate Error
// Stack overflow error via infinite recursion
// Class 1
class StackOverflow {
// method of this class
public static void test( int i)
{
// No correct as base condition leads to
// non-stop recursion.
if (i == 0 )
return ;
else {
test(i++);
}
}
}
// Class 2
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Testing for error by passing
// custom integer as an argument
StackOverflow.test( 5 );
}
}


输出:

例2

JAVA

// Java Program to Illustrate Run-time Errors
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Declaring and initializing numbers
int a = 2 , b = 8 , c = 6 ;
if (a > b && a > c)
System.out.println(a
+ " is the largest Number" );
else if (b > a && b > c)
System.out.println(b
+ " is the smallest Number" );
// The correct message should have been
// System.out.println
// (b+" is the largest Number"); to make logic
else
System.out.println(c
+ " is the largest Number" );
}
}


输出

8 is the smallest Number

现在让我们详细讨论例外情况 哪一个 指示合理的应用程序可能希望捕获的条件。异常是指运行时发生的情况,可能导致程序终止。但它们可以使用try、catch和throw关键字恢复。例外情况分为两类:

编译器在编译时已知的已检查异常(如IOException),而编译器在运行时已知的未检查异常(如ArrayIndexOutOfBoundException)。这主要是由程序员编写的程序引起的。

实例 例外

JAVA

// Java program illustrating exception thrown
// by AritmeticExcpetion class
// Main class
class GFG {
// main driver method
public static void main(String[] args)
{
int a = 5 , b = 0 ;
// Try-catch block to check and handle exceptions
try {
// Attempting to divide by zero
int c = a / b;
}
catch (ArithmeticException e) {
// Displaying line number where exception occured
// using printStackTrace() method
e.printStackTrace();
}
}
}


输出:

图片[2]-Java中的错误与异常-yiteyi-C++库

最后,以如下表格格式绘制出它们之间的差异,从而结束本文:

错误 例外情况
无法从错误中恢复。 我们可以通过使用try-catch块或将异常发回调用方来从异常中恢复。
java中的所有错误都是未经检查的类型。 异常包括选中类型和未选中类型。
错误主要是由程序运行的环境引起的。 程序本身负责导致异常。

错误可能发生在编译时和运行时。编译时:例如语法错误

运行时:逻辑错误。

所有异常都发生在运行时,但编译器知道选中的异常,而不知道未选中的异常。
它们是用java定义的。错误包。 它们是用java定义的。lang.例外包
例子:java。lang.StackOverflowerr,java。lang.OutOfMemoryError 示例:选中的异常:SQLException、IOException未选中的异常:ArrayIndexOutOfBoundException、NullPointerException、算术异常。
© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享