Java中的异常类型及示例

Java定义了与各种类库相关的几种类型的异常。Java还允许用户定义自己的异常。

null

exceptions-in-java

内置异常

内置异常是Java库中可用的异常。这些例外情况适用于解释某些错误情况。下面是Java中重要的内置异常列表。

  1. 算术异常 当算术运算中出现异常情况时抛出。
  2. 数组下标越界异常 抛出它是为了指示数组已被非法索引访问。索引为负数或大于或等于数组的大小。
  3. ClassNotFoundException 当我们试图访问未找到其定义的类时,会引发此异常
  4. FileNotFoundException 当文件不可访问或无法打开时,会引发此异常。
  5. IOException 当输入输出操作失败或中断时,会抛出该命令
  6. 中断异常 当线程正在等待、睡眠或执行某些处理时,会抛出它,并被中断。
  7. Nosuchfield例外 当一个类不包含指定的字段(或变量)时,就会抛出它
  8. NoSuchMethodException 当访问找不到的方法时抛出。
  9. 空指针异常 引用null对象的成员时会引发此异常。Null不代表任何内容
  10. 数字形式异常 当方法无法将字符串转换为数字格式时,会引发此异常。
  11. 运行期异常 这表示运行时发生的任何异常。
  12. StringIndexOutOfBoundsException 它由字符串类方法抛出,以指示索引为负或大于字符串的大小

内置异常的示例:

  • 算术异常

JAVA

// Java program to demonstrate ArithmeticException
class ArithmeticException_Demo
{
public static void main(String args[])
{
try {
int a = 30 , b = 0 ;
int c = a/b; // cannot divide by zero
System.out.println ( "Result = " + c);
}
catch (ArithmeticException e) {
System.out.println ( "Can't divide a number by 0" );
}
}
}


输出:

Can't divide a number by 0
  • 空指针异常

JAVA

//Java program to demonstrate NullPointerException
class NullPointer_Demo
{
public static void main(String args[])
{
try {
String a = null ; //null value
System.out.println(a.charAt( 0 ));
} catch (NullPointerException e) {
System.out.println( "NullPointerException.." );
}
}
}


输出:

NullPointerException..
  • StringIndexOutfound异常

JAVA

// Java program to demonstrate StringIndexOutOfBoundsException
class StringIndexOutOfBound_Demo
{
public static void main(String args[])
{
try {
String a = "This is like chipping " ; // length is 22
char c = a.charAt( 24 ); // accessing 25th element
System.out.println(c);
}
catch (StringIndexOutOfBoundsException e) {
System.out.println( "StringIndexOutOfBoundsException" );
}
}
}


输出:

StringIndexOutOfBoundsException
  • FileNotFound异常

JAVA

//Java program to demonstrate FileNotFoundException
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo {
public static void main(String args[])  {
try {
// Following file does not exist
File file = new File( " E://file.txt " );
FileReader fr = new FileReader(file);
} catch (FileNotFoundException e) {
System.out.println( "File does not exist" );
}
}
}


输出:

File does not exist
  • NumberFormat异常

JAVA

// Java program to demonstrate NumberFormatException
class NumberFormat_Demo
{
public static void main(String args[])
{
try {
// "akki" is not a number
int num = Integer.parseInt ( "akki" ) ;
System.out.println(num);
} catch (NumberFormatException e) {
System.out.println( "Number format exception" );
}
}
}


输出:

Number format exception
  • ArrayIndexOutOfBounds异常

JAVA

// Java program to demonstrate ArrayIndexOutOfBoundException
class ArrayIndexOutOfBound_Demo
{
public static void main(String args[])
{
try {
int a[] = new int [ 5 ];
a[ 6 ] = 9 ; // accessing 7th element in an array of
// size 5
}
catch (ArrayIndexOutOfBoundsException e){
System.out.println ( "Array Index is Out Of Bounds" );
}
}
}


输出:

Array Index is Out Of Bounds

用户定义的异常 有时,Java中的内置异常无法描述特定情况。在这种情况下,用户还可以创建称为“用户定义的异常”的异常。

以下步骤用于创建用户定义的异常。

  • 用户应该创建一个异常类作为异常类的子类。由于所有异常都是Exception类的子类,用户还应该将其类设置为Exception类的子类。具体做法如下:
class MyException extends Exception
  • 我们可以在他自己的异常类中编写默认构造函数。
MyException(){}
  • 我们还可以创建一个参数化构造函数,并将字符串作为参数。 我们可以使用它来存储异常详细信息。我们可以从这里调用超级类(异常)构造函数,并将字符串发送到那里。
MyException(String str){   super(str);}
  • 要引发用户定义类型的异常,我们需要为他的异常类创建一个对象,并使用throw子句抛出它,如下所示:
MyException me = new MyException(“Exception details”);throw me;
  • 下面的程序说明了如何创建自己的异常类MyException。
  • 帐号、客户名称和余额的详细信息以三个数组的形式呈现。
  • 在main()方法中,使用for循环显示详细信息。此时,检查任何账户中的余额是否低于账户中适用的最低余额。
  • 如果是这样,则会引发MyException,并显示一条消息“余额金额较少”。

JAVA

// Java program to demonstrate user defined exception
// This program throws an exception whenever balance
// amount is below Rs 1000
class MyException extends Exception
{
//store account information
private static int accno[] = { 1001 , 1002 , 1003 , 1004 };
private static String name[] =
{ "Nish" , "Shubh" , "Sush" , "Abhi" , "Akash" };
private static double bal[] =
{ 10000.00 , 12000.00 , 5600.0 , 999.00 , 1100.55 };
// default constructor
MyException() {    }
// parameterized constructor
MyException(String str) { super (str); }
// write main()
public static void main(String[] args)
{
try {
// display the heading for the table
System.out.println( "ACCNO" + " " + "CUSTOMER" +
" " + "BALANCE" );
// display the actual account information
for ( int i = 0 ; i < 5 ; i++)
{
System.out.println(accno[i] + " " + name[i] +
" " + bal[i]);
// display own exception if balance < 1000
if (bal[i] < 1000 )
{
MyException me =
new MyException( "Balance is less than 1000" );
throw me;
}
}
} //end of try
catch (MyException e) {
e.printStackTrace();
}
}
}


运行时错误

 MyException: Balance is less than 1000    at MyException.main(fileProperty.java:36)

输出:

ACCNO    CUSTOMER    BALANCE1001    Nish    10000.01002    Shubh    12000.01003    Sush    5600.01004    Abhi    999.0

相关文章:

本文由 尼森特·夏尔马 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

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