更新時間:2022-11-17 12:02:57 來源:動力節點 瀏覽1286次
Java是一種面向對象的編程語言。它提供對異常處理等各種機制的支持。Java 的這一特性使開發人員能夠管理由異常引起的運行時錯誤。
在本文中,您將了解Java中的異常。您還將了解Java 中不同類型的異常。
Java異常是限制程序正常執行的不需要的錯誤或錯誤或事件。每次發生異常時,程序執行都會中斷。屏幕上顯示一條錯誤消息。
異常的發生背后有幾個原因。這些是發生異常的一些情況:
每當用戶提供無效數據時。
請求訪問的文件在系統中不存在。
當Java 虛擬機(JVM) 內存不足時。
網絡在通信過程中掉線。
現在讓我們探索 Java 中不同類型的異常。
所有異常類的父類都是java.lang.Exception類。圖 1 說明了不同類型的 Java 異常。
如果我們談論Exception類,它是內置Throwable類的子類。還有另一個從 Throwable 類派生的子類,即Error,如圖 1 所示。錯誤可以定義為一種異常情況,表明程序的執行出現了問題。這些不是由 Java 程序處理的。
Throwable類中有一些重要的方法可用,如下所示:
public String getMessage() – 提供有關通過消息發生的異常的信息,該消息在Throwable 構造函數中初始化。
public Throwable getCause() – 提供由Throwable 對象表示的異常的根本原因。
public void printStackTrace() – 用于顯示toString()的輸出以及到System.err(錯誤輸出流)的堆棧跟蹤。
public StackTraceElement [] getStackTrace() – 返回一個數組,其中包含堆棧跟蹤中存在的每個元素。索引 0 元素將象征調用堆棧的頂部,數組的最后一個元素將標識調用堆棧的底部。
Java中主要有以下兩種類型的異常:
檢查異常
未經檢查的異常
檢查異常也稱為編譯時異常,因為這些異常在編譯過程中由編譯器檢查,以確認程序員是否處理了異常。如果不是,則系統顯示編譯錯誤。例如,SQLException、IOException、InvocationTargetException和ClassNotFoundException。
為了說明檢查異常的概念,讓我們考慮以下代碼片段:
import java.io.*;
class demo1 {
public static void main(String args[]) {
FileInputStream input1 = null;
/* FileInputStream(File filename) is a constructor that will throw
* FileNotFoundException (a checked exception)
*/
input1 = new FileInputStream("D:/file.txt");
int m;
// The read() of FileInputStream will also throw a checked exception
while(( m = input1.read() ) != -1) {
System.out.print((char)m);
}
// The close() will close the file input stream, and it will also throw a exception
input1.close();
}
}
輸出
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Unhandled exception type FileNotFoundException
Unhandled exception type IOException
Unhandled exception type IOException
輸出中清楚地顯示程序在編譯過程中拋出異常。有兩種方法可以解決此類問題。您可以在throw關鍵字的幫助下聲明異常。
import java.io.*;
class demo1 {
public static void main(String args[]) throws IOException {
FileInputStream input1 = null;
input1 = new FileInputStream("D:/file.txt");
int m;
while ((m = input1.read()) != -1) {
System.out.print((char)m);
}
input1.close();
}
}
輸出:文件將顯示在屏幕上。
除了上述方法外,還有一種解決異常的方法。您可以在try-catch 塊的幫助下管理它們。
import java.io.*;
class demo1 {
public static void main(String args[]) {
FileInputStream input1 = null;
try {
input1 = new FileInputStream("D:/file.txt");
} catch(FileNotFoundException input2) {
system.out.println("The file does not " + "exist at the location");
}
int m;
try {
while((m = input1.read()) != -1) {
System.out.print((char)m);
}
input1.close();
} catch(IOException input3) {
system.out.println("I/O error occurred: "+ input3);
}
}
}
輸出:代碼將順利運行并顯示文件。
現在,讓我們了解其他檢查異常。他們之中有一些是:
此類異常發生在對與 SQL 語法相關的數據庫執行查詢時。例如,考慮以下代碼片段:
public void setClientInfo ( String sname , String svalue ) throws SQLClientInfoException { try {
checkClosed (); ((java.sql.Connection)這個.mc)。_ _ _ setClientInfo (名稱,值); } catch ( SQLException sqlEx ) { try {
checkAndFireConnectionError ( sqlEx );
} catch ( SQLException sqlEx2 ) { SQLClientInfoException client_Ex = new SQLClientInfoException ();
client_Ex 。初始化原因(sqlEx2 );拋出client_Ex ;} } }
輸出:此代碼將生成 SQLException。
這種類型的異常發生在使用文件 I/O 流操作時。例如,考慮以下代碼片段:
import java.io.*;
public class sample_IOException {
private static String filepath = "D:\User\guest\Desktop\File2.txt";
public static void main(String[] args) {
BufferedReader br1 = null;
String curline;
try {
br1 = new BufferedReader(new FileReader(filepath));
while ((curline = br1.readLine()) != null) {
System.out.println(curline);
}
} catch (IOException e) {
System.err.println("IOException found :" + e.getMessage());
} finally {
try {
if (br1 != null)
br1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
輸出:此代碼將生成 IOException。
當 JVM 無法找到所需的類時,將拋出此類異常。這可能是由于命令行錯誤、類路徑問題或缺少 .class 文件造成的。例如,考慮以下代碼片段:
public class sample_ClassNotFoundException {
private static final String CLASS_TO_LOAD = "main.java.Utils";
public static void main(String[] args) {
try {
Class loadedClass = Class.forName(CLASS_TO_LOAD);
System.out.println("Class " + loadedClass + " found!");
} catch (ClassNotFoundException ex) {
System.err.println("ClassNotFoundException was found: " + ex.getMessage());
ex.printStackTrace();
}
}
}
輸出:此代碼將生成 ClassNotFoundException。
這種類型的異常包裝由調用的方法或構造函數拋出的異常。可以借助getTargetException方法訪問拋出的異常。例如,考慮以下代碼片段:
package main.samplejava;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Example {
@SuppressWarnings("unused")
private int test_sample(String s1) {
if (s1.length() == 0)
throw new IllegalArgumentException("The string should have at least one character!");
System.out.println("Inside test_sample: argument's value equals to: "" + s1 + """);
return 0;
}
public static void main(String... args) {
try {
Class<?> c1 = Class.forName("main.samplejava. Example");
Object t1 = c1.newInstance();
Method[] declared_Methods = c1.getDeclaredMethods();
for (Method method : declared_Methods) {
String methodName = method.getName();
if (methodName.contains("main"))
continue;
System.out.format("Invoking %s()%n", methodName);
try {
method.setAccessible(true);
Object returnValue = method.invoke(t1, "");
System.out.format("%s() returned: %d%n", methodName, returnValue);
} catch (InvocationTargetException ex) {
System.err.println("An InvocationTargetException was caught!");
Throwable cause = ex.getCause();
System.out.format("Invocation of %s failed because of: %s%n",
methodName, cause.getMessage());
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
System.err.println("The following exception was thrown:");
ex.printStackTrace();
}
}
}
輸出
Invoking testMethod()
An InvocationTargetException was caught!
Invocation of testMethod failed because of: The string must contain at least one character!
輸出:此代碼將生成 InstantiationException。
未經檢查的異常是在程序執行期間發生的那些異常。因此它們也被稱為運行時異常。這些異常在編譯過程中一般會被忽略。編譯程序時不檢查它們。例如,邏輯錯誤和使用不正確的 API 等編程錯誤。
為了說明未經檢查的異常的概念,讓我們考慮以下代碼片段:
import java.util.Scanner;
public class Sample_RunTimeException {
public static void main(String[] args) {
// Reading user input
Scanner input_dev = new Scanner(System.in);
System.out.print("Enter your age in Numbers: ");
int age1 = input_dev.nextInt();
if (age1>20) {
System.out.println("You can view the page");
} else {
System.out.println("You cannot view the page");
}
}
}
輸出1
Enter your age in Numbers: 21
You can view the page
輸出2
Enter your age in Numbers: Twelve
Exception in thread “main” java.util.InputMismatchException
at java.util.Scanner.throwFor (Unknown Source)
at java.util.Scanner.next (Unknown Source)
at java.util.Scanner.nextInt (Unknown Source)
at java.util.Scanner.nextInt (Unknown Source)
at exceptiondemo.sample_runtimedemo.main(Sample_RunTimeExceptionDemo.java:11)
現在,讓我們了解其他未檢查的異常。他們之中有一些是:
當您嘗試借助當前值為 null 或空的引用變量訪問對象時,會發生此類異常。例如,考慮以下代碼片段:
// Program to demonstrate the NullPointerException
class SampleNullPointer {
public static void main(String args[]) {
try {
String a1 = null; // null value
System.out.println(a1.charAt(0));
} catch(NullPointerException e) {
System.out.println("NullPointerException is found in the program.");
}
}
}
輸出:在程序中發現 NullPointerException。
當您嘗試訪問具有無效索引值的數組時,會發生此類異常。您提供的值是負數或超出數組的長度。
例如,考慮以下代碼片段:
// Program to demonstrate the ArrayIndexOutOfBoundException
class sample_ArrayIndexOutOfBound {
public static void main(String args[]) {
try {
int b[] = new int[6];
b[8] = 2; // we are trying to access 9th element in an array of size 7
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println ("The array index is out of bound");
}
}
}
輸出:數組索引越界
每當將不適當或不正確的參數傳遞給方法時,就會發生這種類型的異常。例如,如果一個方法是用非空字符串作為參數定義的。但是您提供的是空輸入字符串。然后,拋出 IllegalArgumentException以指示用戶您不能將空輸入字符串傳遞給該方法。
請考慮以下代碼片段來演示此類異常:
import java.io.File;
public class Sample_IllegalArgumentException {
public static String createRelativePath(String par, String f_name) {
if (par == null)
throw new IllegalArgumentException("You cannot provide null parent path!");
if (f_name == null)
throw new IllegalArgumentException("Please enter the complete filename!");
return par + File.separator + f_name;
}
public static void main(String[] args) {
// This command will be successfully executed.
system.out.println(IllegalArgumentExceptionExample.createRelativePath("dir1", "file1"));
system.out.println();
// This command will throw an IllegalArgumentException.
System.out.println(IllegalArgumentExceptionExample.createRelativePath(null, "file1"));
}
}
Output: This code will generate an IllegalArgumentException.
當環境狀態與正在執行的操作不匹配時,就會發生這種類型的異常。例如,考慮下面的代碼片段,它演示了這種類型的異常:
/**
* This code will publish the current book.
* If the book is already published, it will throw an IllegalStateException.
**/
public void pub() throws IllegalStateException {
Date pub_at = getPub_at();
if (pub_at == null) {
setPub_at(new Date());
Logging.log(String.format("Published '%s' by %s.", getTitle(), getAuthor()));
} else {
throw new IllegalStateException(
String.format("Cannot publish '%s' by %s (already published on %s).",
getTitle(), getAuthor(), pub_at));
}
}
輸出:此代碼將生成 IllegalStateException。
如果系統中已經存在出版日期,那么它將產生一個 IllegalStateException 指示該書不能再次出版。
當您將字符串傳遞給無法轉換為數字的方法時,會發生此類異常。例如,考慮以下代碼片段:
// Program to demonstrate the NumberFormatException
class Sample_NumberFormat {
public static void main(String args[]) {
try {
// "Test" is not a number
int n = Integer.parseInt ("Test") ;
System.out.println(n);
} catch(NumberFormatException e) {
System.out.println("Number format exception");
}
}
}
輸出:此代碼將生成 NumberFormatException。
當您執行不正確的算術運算時,會發生這種類型的異常。比如任意一個數除以零,就會顯示這樣的異常。讓我們考慮以下代碼片段:
// Program to demonstrate the ArithmeticException
class Sample_ArithmeticException {
public static void main(String args[]) {
try {
int p = 30, q = 0;
int r = p/q; // It cannot be divided by zero
System.out.println ("Result = " + r);
} catch(ArithmeticException e) {
System.out.println ("Number cannot be divided by 0");
}
}
}
輸出:此代碼將生成一個 ArithmeticException。
以上就是關于“Java異常類型匯總”的介紹,大家如果想了解更多相關知識,不妨來關注一下本站的Java基礎教程,里面的課程內容細致全面,很適合沒有基礎的小伙伴學習,希望對大家能夠有所幫助哦。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習