Heim > Java > javaLernprogramm > Hauptteil

Mehrfach-Catch-Block in Java

王林
Freigeben: 2024-08-30 15:11:46
Original
471 Leute haben es durchsucht

We can handle exceptions inside our code by inserting try-catch blocks in java. Here in this article, we will see how we can handle multiple exceptions for a single try block by using multiple catch blocks or multiple arguments for a catch block.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax

Syntax of Multiple Catch Block in Java are given below:

Syntax 1: simple try-catch block

try
{
//code snippet which might responsible for exceptions
}
catch (<type_of_exception> <name_of_exception_object>)‏
{
//here we handle exceptions
}
Nach dem Login kopieren

Syntax 2: try-catch block with multiple catch block

try
{
//code snippet which might responsible for exceptions
}
catch (<type_of_exception> <name_of_exception_object>)‏ //catch block 1
{
//here we handle exceptions
}
catch (<type_of_exception> <name_of_exception_object>)‏ //catch block 2
{
//here we handle exceptions
}
catch (<type_of_exception> <name_of_exception_object>)‏ //catch block 3
{
//here we handle exceptions
}
Nach dem Login kopieren

Syntax 3: try-catch block with multiple catch statements as argument of the catch block

try
{
//code snippet which might responsible for exceptions
}
catch (<type_of_exception1> | <type_of_exception2> | <type_of_exception3> <name_of_exception_object>)‏
{
//here we handle exceptions
}
Nach dem Login kopieren

How Catch Block Work in Java?

At first, we need to check on the try block before moving to catch block.

1. Try Block

It contains the code snippet which may result in exceptions. So, whenever you suspect that your code might result in an exception, put that code snippet inside a try block. At least one catch block is necessary for a try block.

2. Catch Block

It contains the code snippet which handles the exception that might occur for the code which is written inside its corresponding try block. Now how to deal with multiple exceptions, if any?

You can take two ways:

  • Use Multiple Catch for a Try Block: Here you can handle multiple exceptions under multiple catch block for a corresponding try block. Program flow will automatically come to the catch block one by one and then, the corresponding catch block is found as per the exception and will be handled accordingly.
  • Use Multiple Catch Statements in Arguments of A Catch Block: This feature came from Java 7. Here you can handle multiple exceptions under a single catch block (separated by pipe sign) for a corresponding try block. Program flow will automatically come to the catch block and then, the corresponding exception inside the arguments of catch block is found for the try block and will be handled accordingly.

Constructor

We also can write try-catch blocks inside a constructor and it will work as expected. In the below example, we will write code inside try constructor: try block will generate arithmetic exception which is handled in a catch block.

public class MultipleCatchBlockInConstructor
{
MultipleCatchBlockInConstructor()
{
try
{
int num=6/0;
}
catch(ArrayIndexOutOfBoundsException excp)
{
System.out.println("Exception is : "+excp);
}
catch(ArithmeticException excp)
{
System.out.println("Exception is : "+ excp);
}
}
public static void main(String[] args) {
MultipleCatchBlockInConstructor mc=new MultipleCatchBlockInConstructor();
}
}
Nach dem Login kopieren

Output:

Mehrfach-Catch-Block in Java

Examples of Multiple Catch Block in Java

In this section, we will discuss many code examples. You should try this code by yourself and tally the outputs with the given one.

Example #1

This is a simple example of a multi-catch block, where we have written a statement that will generate exceptions inside try block, which will be handled by a corresponding catch block out of three catch blocks.

Code:

public class MultipleCatchBlockInJava {
public static void main(String[] args) {
try{
System.out.println("start of try block");
int num = 6/0;
}
catch(ArithmeticException e)
{
System.out.println("divide by zero exception ");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Any other excpetion");
}
System.out.println("end of try-catch block");
}
}
Nach dem Login kopieren

Output:

Mehrfach-Catch-Block in Java

Example #2

In this example, we have illustrated about out-of-bound exception handing for an array by try and catch block.

Code:

public class MultipleCatchBlockInJava {
public static void main(String[] args) {
try{
System.out.println("start of try block");
int arr[]=new int[6];
System.out.println(arr[12]); //we want to access 12th element of array which does not exist as size is of 6
}
catch(ArithmeticException e)
{
System.out.println("divide by zero exception");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array IndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Any other exception");
}
System.out.println("end of try-catch block");
}
}
Nach dem Login kopieren

Output:

Mehrfach-Catch-Block in Java

Example #3

In this example, we will see how the null pointer is handled by a catch block. Also, note that there are multiple scenarios of exceptions in the try block, but once program flow reaches to first exception generating statement (here, Nullpointer exception), it will immediately move out of try block and searches the exception handler in a catch block. The other exception generating statement (here, Array index out of bound exception) inside try block is ignored.

Code:

public class MultipleCatchBlockInJava {
public static void main(String[] args) {
try{
System.out.println("start of try block");
String str=null;
System.out.println(str.length());  //we want to get length of a null string
int arr[]=new int[6];
System.out.println(arr[12]); //we want to access 12th element of array which does not exist as size is of 6
}
catch(ArithmeticException e)
{
System.out.println("divide by zero exception");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array IndexOutOfBounds Exception occurs");
}
catch(NullPointerException e)
{
System.out.println("Null pointer Exception occurs");
}
System.out.println("end of try-catch block");
}
}
Nach dem Login kopieren

Output:

Mehrfach-Catch-Block in Java

Example #4

In this example, we will check how exception will be handled by multiple arguments of a single catch block.

Code:

public class MultipleCatchBlockInJava {
public static void main(String[] args) {
try{
System.out.println("start of try block");
String str=null;
System.out.println(str.length());  //we want to get length of a null string
int arr[]=new int[6];
System.out.println(arr[10]); //we want to access 10th element of array which does not exist as size is of 6
}
catch(ArithmeticException | ArrayIndexOutOfBoundsException | NullPointerException e )
{
System.out.println("Code is throwing " + e);
}
System.out.println("end of try-catch block");
}
}
Nach dem Login kopieren

Output:

Mehrfach-Catch-Block in Java

Conclusion

This concludes our learning for multiple catch blocks from in the java programming perspective. To summarize: Whenever you need to handle multiple exceptions, you can write those inside multiple catch blocks. Alternatively, for java 7 and above you can write multiple exceptions in arguments single catch block and program flow will automatically pick this. Also, it is important that you should write codes by yourself for better understanding.

Das obige ist der detaillierte Inhalt vonMehrfach-Catch-Block 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!