Heim > Java > javaLernprogramm > Hauptteil

Arten von Ausnahmen in Java

WBOY
Freigeben: 2024-08-30 16:12:33
Original
249 Leute haben es durchsucht

Der folgende Artikel bietet einen Überblick über Ausnahmetypen in Java. Java Exception spielt zum Zeitpunkt der Programmausführung eine sehr entscheidende Rolle. Im Allgemeinen führt jedes Programm mit einer abnormalen Beendigung oder Unterbrechung zum Zeitpunkt der Ausführung zu einer Ausnahme. Eine Java-Ausnahme entsteht zum Zeitpunkt der Objekterstellung, wenn eine Ausnahme auftritt oder ein Fehler zur Laufzeit verursacht wird und Ausnahmen mit den Objekten in Java zusammenhängen, da es sich um eine objektorientierte Programmiersprache handelt. Daher gibt es eine Hierarchie der Ausnahmen und Fehler mit auslösbaren, Try-and-Catch-Blöcken, um die verursachte Ausnahme abzufangen und zu identifizieren.

Starten Sie Ihren kostenlosen Softwareentwicklungskurs

Webentwicklung, Programmiersprachen, Softwaretests und andere

Verschiedene Arten von Ausnahmen in Java

Die Objekterstellung im Java-Programm, die für die Art der Ausnahme verantwortlich ist, folgt einer Hierarchie, die wie folgt dargestellt wird:

Arten von Ausnahmen in Java

Ausnahmen in Java während der Programmierung werden grundsätzlich in zwei Kategorien unterteilt, wie zum Beispiel:

  • Eingebaute Ausnahmen: Dies sind die Arten von Ausnahmen, die mit bereits vorhandenen Java-Bibliotheken abgefangen werden können. Sie wird auch als ungeprüfte Ausnahme oder Laufzeitausnahme bezeichnet.
  • Benutzerdefinierte Ausnahmen: Dies sind die Arten von Ausnahmen, die mit einigen der vom Benutzer erstellten benutzerdefinierten Ausnahmen abgefangen werden können, und der Benutzer sollte die Möglichkeit haben, diese Ausnahmen zu behandeln. Diese Ausnahmen können auch als Checked Exception oder Compile Time Exception bezeichnet werden.

1. Arten von integrierten Ausnahmen

  • Arithmetische Ausnahme
  • ClassNotFoundException
  • IOException
  • ArrayIndexOutOfBoundsException
  • FileNotFoundException
  • NullPointerException
  • NoSuchFieldException
  • NoSuchMethodException
  • StringIndexOutOfBoundsException
  • RuntimeException
  • NumberFormatException
  • InterruptedException
a. Arithmetische Ausnahme

Diese Ausnahme wird immer dann aufgerufen, wenn zum Zeitpunkt der arithmetischen Berechnung eine Abweichung vorliegt.

Beispiel:

Dieses Programm demonstriert die arithmetische Ausnahme.

Code:

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.");
}
}
}
}
Nach dem Login kopieren

Ausgabe:

Arten von Ausnahmen in Java

b. ClassNotFoundException

Wenn eine Klasse nicht richtig definiert ist, führt dies zu einer ClassNotFoundException.

Beispiel:

Dieses Programm demonstriert die ClassNotFoundException.

Code:

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);
}
}
Nach dem Login kopieren

Ausgabe:

Arten von Ausnahmen in Java

c. IO-Ausnahme

Wenn eine Ein- oder Ausgabe abnormal beendet wird und der Vorgang fehlschlägt, führt dies zu einer E/A-Ausnahme.

Beispiel:

Dieses Programm demonstriert die IO-Ausnahme.

Code:

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();
}
}
Nach dem Login kopieren

Ausgabe:

Arten von Ausnahmen in Java

d. ArrayIndexOutOfBoundsException

Immer wenn auf einen falschen Index zugegriffen wird und der Bereich des Index nicht erreichbar ist und nicht darauf zugegriffen werden kann, wird eine ArrayIndexOutOfBoundsException ausgegeben

Beispiel:

Dieses Programm demonstriert die ArrayIndexOutOfBoundsException.

Code:

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.");
}
}
}
Nach dem Login kopieren

Ausgabe:

Arten von Ausnahmen in Java

z.B. FileNotFoundException

Wenn eine Datei nicht richtig im Pfad erwähnt wird oder nicht richtig geöffnet wird, wird eine FileNotFoundException ausgelöst

Beispiel:

Dieses Programm demonstriert die FileNotFoundException.

Code:

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();
}
}
}
}
Nach dem Login kopieren

Ausgabe:

Arten von Ausnahmen in Java

f. Nullzeiger-Ausnahme

Diese Art von Ausnahme tritt immer dann auf, wenn die Mitglieder des Objekts auf einen Nullwert verweisen oder darauf verweisen.

Beispiel:

Dieses Programm demonstriert die Nullzeiger-Ausnahme.

Code:

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.");
}
}
}
Nach dem Login kopieren

Ausgabe:

Arten von Ausnahmen in Java

g. NoSuchFieldException

Diese Ausnahme tritt immer dann auf, wenn kein Feld oder eine Variable vorhanden ist.

Beispiel:

Dieses Programm demonstriert die NoSuchFieldException.

Code:

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.";
}
Nach dem Login kopieren

Ausgabe:

Arten von Ausnahmen in Java

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();
}
}
}
Nach dem Login kopieren

Output:

Arten von Ausnahmen in Java

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.");
}
}
}
Nach dem Login kopieren

Output:

Arten von Ausnahmen in Java

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();
}
}
Nach dem Login kopieren

Output:

Arten von Ausnahmen in Java

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");
}
}
}
Nach dem Login kopieren

Output:

Arten von Ausnahmen in Java

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();
}
}
Nach dem Login kopieren

Output:

Arten von Ausnahmen in Java

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 < 4 ; i++)
{
System.out.println(roll_no[i] + "\t" + student_Nm[i] +
"\t" + marks[i]);
if (marks[i] < 60)
{
My_Excpn mrk1 =
new My_Excpn("Student will fail if marks is less than 60");
throw mrk1;
}
}
}
catch (My_Excpn excpn) {
excpn.printStackTrace();
}
}
}
Nach dem Login kopieren

Output:

Arten von Ausnahmen in Java

Conclusion

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.

Das obige ist der detaillierte Inhalt vonArten von Ausnahmen in Java. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Verwandte Etiketten:
Quelle:php
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!