以下文章概述了 Java 中的异常类型。 Java异常在程序执行时起着非常关键的作用。一般来说,任何程序在执行时异常终止或中断都会导致异常。 Java Exception 是在创建对象时出现异常,或者是运行时发生错误,而异常与 Java 中的对象有关,因为它是面向对象的编程语言。因此,存在一个异常和错误的层次结构,其中包含 throwable、try 和 catch 块来捕获和识别引起的异常。
开始您的免费软件开发课程
网络开发、编程语言、软件测试及其他
Java 中不同类型的异常
Java 程序中负责异常类型的对象创建遵循层次结构,如下所示:
java 编程时的异常基本上分为两类,例如:
- 内置异常:这些是可以使用现有 Java 库捕获的异常类型。它也称为未检查异常或运行时异常。
- 用户定义的异常:这些异常类型可以使用用户创建的一些自定义异常来捕获,并且用户应该有能力处理这些异常。这些异常也可以称为检查异常或编译时异常。
1.内置异常的类型
- 算术异常
- ClassNotFoundException
- IOException
- ArrayIndexOutOfBoundsException
- FileNotFoundException
- 空指针异常
- NoSuchFieldException
- NoSuchMethodException
- StringIndexOutOfBoundsException
- 运行时异常
- NumberFormatException
- 中断异常
a.算术异常
每当算术计算时出现某些不匹配时,就会调用此异常。
示例:
该程序演示了算术异常。
代码:
public class Arithmtic_excpn { public static void main(String[] args) { { try { int first_no = 0; int scnd_no = 20; int third_no = 0; int fourth_no = (first_no-scnd_no)/third_no; System.out.println ("output after the operation " + fourth_no ); } catch(ArithmeticException arithmetic_ex) { System.out.println ("The third number cannot store the value of first number multiplied by second number."); } } } }
输出:
b. ClassNotFoundException
如果任何类未正确定义,则会导致 ClassNotFoundException。
示例:
该程序演示了 ClassNotFoundException。
代码:
public class Not_Found_Excp { private static final String mysql_connector = "com.jdbc.mysql-connector"; public static void main(String[] args) throws Exception { System.out.println("search for the mysql-connector of jdbc for establishing connection."); Class.forName(mysql_connector); } }
输出:
c. IO异常
当任何一个输入或输出异常终止并且操作失败时,就会导致 IO 异常。
示例:
该程序演示了 IO 异常。
代码:
import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class IO_Excption_Ex { public FileInputStream testMethod1(){ File file_a = new File("123.txt"); FileInputStream fileInptstrm = null; try{ fileInptstrm = new FileInputStream(file_a); fileInptstrm.read(); }catch (IOException excpn){ excpn.printStackTrace(); } finally{ try{ if (fileInptstrm != null){ fileInptstrm.close(); } }catch (IOException excpn){ excpn.printStackTrace(); } } return fileInptstrm; } public static void main(String[] args){ IO_Excption_Ex inst_1 = new IO_Excption_Ex(); inst_1.testMethod1(); } }
输出:
d. ArrayIndexOutOfBoundsException
每当访问错误的索引,并且索引的范围不可达,无法访问时,就会出现ArrayIndexOutOfBoundsException
示例:
此程序演示了 ArrayIndexOutOfBoundsException。
代码:
public class Arr_Indx_Out_Of_BOnd { public static void main(String[] args) { try{ int ar_0[] = new int[6]; ar_0[8] = 11; } catch(ArrayIndexOutOfBoundsException excp){ System.out.println ("Index of the array has crossed the range."); } } }
输出:
e.文件未找到异常
如果路径中未正确提及任何文件或未正确打开任何文件,则会抛出 FileNotFoundException
示例:
该程序演示了 FileNotFoundException。
代码:
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; public class File_Not_Found_Excpt_Exmpl { private static final String file_nm = "jkl.txt"; public static void main(String[] args) { BufferedReader rder = null; try { rder = new BufferedReader(new FileReader(new File(file_nm))); String inpt_ln = null; while ((inpt_ln = rder.readLine()) != null) System.out.println(inpt_ln); } catch (IOException excpn) { System.err.println("catch the IO Exception."); excpn.printStackTrace(); } finally { try { rder.close(); } catch (IOException excpn) { System.err.println("catch the IO Exception."); excpn.printStackTrace(); } } } }
输出:
f.空指针异常
只要对象的成员指向或引用任何空值,就会发生这种类型的异常。
示例:
该程序演示了空指针异常。
代码:
public class Null_Pointer_Excp { public static void main(String[] args) { try { String art_1 = null; String art_3= "abc"; System.out.println(art_1.charAt(0)); } catch(NullPointerException excpn) { System.out.println("This will give a null pointer exception."); } } }
输出:
g。 NoSuchFieldException
只要不存在字段或存在任何变量,就会发生此异常。
示例:
此程序演示了 NoSuchFieldException。
代码:
import java.text.DateFormat.Field; import java.lang.reflect.*; public class No_suc_field_excpn_Ex { public static void main(String[] args) { No_suc_field_excpn_Ex excp = new No_suc_field_excpn_Ex(); Class any_cls = excp.getClass(); System.out.println("value_of_field="); try { java.lang.reflect.Field strng_fld = any_cls.getField("One_strng"); System.out.println("field for the public superclass is found: " + strng_fld.toString()); } catch(NoSuchFieldException excpn) { System.out.println(excpn.toString()); } } public No_suc_field_excpn_Ex() { } public No_suc_field_excpn_Ex(String One_strng) { this.val_OneStrng = One_strng; } public String val_OneStrng = "Everything appears to be Exception."; }
输出:
h. NoSuchMethodException
While trying to access any method in a class and that method is not defined clearly or else is missing will lead to NoSuchMethodException.
Example:
This program demonstrates the NoSuchMethodException.
Code:
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class No_Sch_mthd_Ex { public static String add_rss; public static String somefiletext; public static String initial_page_src; public static void Calculate() throws MalformedURLException { URL url_a = new URL(add_rss) ; URLConnection connect_2 = null; try { connect_2 = url_a.openConnection(); } catch (IOException excp) { excp.printStackTrace(); } BufferedReader buffrr = null; try { buffrr = new BufferedReader( new InputStreamReader(connect_2.getInputStream())); } catch (IOException excpn) { excpn.printStackTrace(); } String filnm_z = "C:\\Users\\adutta\\Documents\\"+"page_src"+"123.txt"; File file_o = new File(filnm_z); if (!file_o.exists()) { try { file_o.createNewFile(); } catch (IOException excpn) { excpn.printStackTrace(); } } FileWriter flwrtr = null; try { flwrtr = new FileWriter(filnm_z); } catch (IOException exc) { exc.printStackTrace(); } BufferedWriter bw = new BufferedWriter(flwrtr); String textreader; try { while ((textreader = buffrr.readLine()) != null) { bw.write(textreader); } } catch (IOException excn) { excn.printStackTrace(); } } public static void set_page_src(String page_src){ page_src = initial_page_src; } public static void set_url(String addressname){ addressname = add_rss; } public static void set_text_file_name(String celeb_filename_p){ celeb_filename_p = celeb_name_i; } public static String celeb_name_i = "type_the_text" ; public static String url_add_ress = "http//ooo.com"; public static void main(String[] args) { No_Sch_mthd_Ex.set_page_src(celeb_name_i); No_Sch_mthd_Ex.set_url(url_add_ress); try { No_Sch_mthd_Ex.Calculate(); } catch (IOException excpn) { excpn.printStackTrace(); } } }
Output:
i. StringIndexOutOfBoundsException
If the index ranging is negative or more than the defined index range in the string class, then it will result into this exception of StringIndexOutOfBoundsException.
Example:
This program demonstrates the StringIndexOutOfBoundsException.
Code:
public class String_Inx_Out_Of_Bound_Ex { public static void main(String[] args) { try { String ant = "ant crawls very slowly."; char chrct = ant.charAt(50); System.out.println(chrct); } catch(StringIndexOutOfBoundsException excepn) { System.out.println("String_Out_Of_Bound_Exception occured."); } } }
Output:
j. RuntimeException
During runtime if any kind of exception arise then these types of exceptions are known as RuntimeException.
Example:
This program demonstrates the RuntimeException.
Code:
public class Runtime_Excp_Ex { public void Demo_Runtime_Exception () { throw new Running_Exception(); } public static void main(String[] args) { try { new Running_Exception().Demo_Runtime_Exception(); } catch(Exception excpn) { System.out.println(excpn.getClass().getName()); } } } class Running_Exception extends RuntimeException { public Running_Exception() { super(); } public void Demo_Runtime_Exception() { throw new Running_Exception(); } }
Output:
k. NumberFormatException
Any exception which cannot get converted into numeric format from the string defined then it will lead to NumberFormatException.
Example:
This program demonstrates the NumberFormatException.
Code:
public class No_Format_Ex { public static void main(String[] args) { try { int value1 = Integer.parseInt ("parasite1") ; System.out.println(value1); } catch(NumberFormatException excepn) { System.out.println("This gives Number Format Exception"); } } }
Output:
l. InterruptedException
If a thread gets disturbed at the time of waiting, sleeping or while performing some processing then it leads to interrupted Exception.
Example:
This program demonstrates the InterruptedException.
Code:
class ChildThread extends Thread { public void run() { try { Thread.sleep(500); } catch (InterruptedException excpn) { System.err.println("Interuppted_Exception occured."); excpn.printStackTrace(); } } } public class Interuupted_Excpt_Exmple { public static void main(String[] args) throws InterruptedException { ChildThread chldth1 = new ChildThread(); chldth1.start(); chldth1.interrupt(); } }
Output:
2. User-Defined Exception
This exception occurs whenever there is some customizable or errors done by user while implementation and execution of program.
Example:
This program demonstrates the user-Defined Exception.
Code:
public class My_Excpn extends Exception { private static int roll_no[] = {10, 15, 23, 30}; private static String student_Nm[] = {"ani", "viky", "nidhi", "ash"}; private static double marks[] = {20.5, 44.6, 30, 17}; My_Excpn() { } My_Excpn(String str) { super(str); } public static void main(String[] args) { try { System.out.println("roll_no" + "\t" + "student_Nm" + "\t" + "marks"); for (int i = 0; i <p><strong>Output:</strong></p> <p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172500559336989.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Java 中的异常类型" ></p> <h3 id="Conclusion">Conclusion</h3> <p>Exceptions in java plays a very pivotal role because it helps in catching and simultaneously throwing of the root cause for an abnormal termination of the program. It often causes and consumes a lot of time for programmers to run and execute programs therefore these kinds of fatal exceptions should not occur frequently at the time of production or even implementation.</p>
以上是Java 中的异常类型的详细内容。更多信息请关注PHP中文网其他相关文章!

Java在企业级应用中被广泛使用是因为其平台独立性。1)平台独立性通过Java虚拟机(JVM)实现,使代码可在任何支持Java的平台上运行。2)它简化了跨平台部署和开发流程,提供了更大的灵活性和扩展性。3)然而,需注意性能差异和第三方库兼容性,并采用最佳实践如使用纯Java代码和跨平台测试。

JavaplaysigantroleiniotduetoitsplatFormentence.1)itallowscodeTobewrittenOnCeandrunonVariousDevices.2)Java'secosystemprovidesuseusefidesusefidesulylibrariesforiot.3)

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

Java'splatFormIndenceistificantBecapeitAllowSitallowsDevelostWriTecoDeonCeandRunitonAnyPlatFormwithAjvm.this“ writeonce,runanywhere”(era)橱柜橱柜:1)交叉plat formcomplibility cross-platformcombiblesible,enablingDeploymentMentMentMentMentAcrAptAprospOspOspOssCrossDifferentoSswithOssuse; 2)

Java适合开发跨服务器web应用。1)Java的“一次编写,到处运行”哲学使其代码可在任何支持JVM的平台上运行。2)Java拥有丰富的生态系统,包括Spring和Hibernate等工具,简化开发过程。3)Java在性能和安全性方面表现出色,提供高效的内存管理和强大的安全保障。

JVM通过字节码解释、平台无关的API和动态类加载实现Java的WORA特性:1.字节码被解释为机器码,确保跨平台运行;2.标准API抽象操作系统差异;3.类在运行时动态加载,保证一致性。

Java的最新版本通过JVM优化、标准库改进和第三方库支持有效解决平台特定问题。1)JVM优化,如Java11的ZGC提升了垃圾回收性能。2)标准库改进,如Java9的模块系统减少平台相关问题。3)第三方库提供平台优化版本,如OpenCV。

JVM的字节码验证过程包括四个关键步骤:1)检查类文件格式是否符合规范,2)验证字节码指令的有效性和正确性,3)进行数据流分析确保类型安全,4)平衡验证的彻底性与性能。通过这些步骤,JVM确保只有安全、正确的字节码被执行,从而保护程序的完整性和安全性。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

禅工作室 13.0.1
功能强大的PHP集成开发环境

SublimeText3 Linux新版
SublimeText3 Linux最新版