Mẹo Hướng dẫn What symbol S is used to separate multiple exceptions in one catch statement? Chi Tiết
Bùi Trung Huấn đang tìm kiếm từ khóa What symbol S is used to separate multiple exceptions in one catch statement? được Cập Nhật vào lúc : 2022-12-21 03:16:08 . Với phương châm chia sẻ Kinh Nghiệm Hướng dẫn trong nội dung bài viết một cách Chi Tiết 2022. Nếu sau khi Read nội dung bài viết vẫn ko hiểu thì hoàn toàn có thể lại Comment ở cuối bài để Admin lý giải và hướng dẫn lại nha.In this post we'll talk about multi-catch statement in Java exception handling along with examples to see how to handle more than one type of exception in single catch block using multi-catch statement.
Nội dung chính Show- Handling more than one type of exception without multi-catch statementJava multi-catch - Handling more than one type of exceptionJava Multi-catch statement means better codeMulti-catch statement & Exception hierarchyExample 1: Multiple catch blocksExample 2: Multi-catch blockCatching base ExceptionExample 3: Catching base exception class onlyExample 4: Catching base and child exception classesHow multiple catch statements are used in exceptions?How to catch multiple exceptions once in C#?Which keyword is used to throw multiple exceptions once?Can you throw multiple exceptions in one throw statement?
Handling more than one type of exception without multi-catch statement
Before Java 7 multi-catch statement, if two or more exceptions were handled in the same way, we still had to write separate catch blocks for handling them.
catch(IOException exp) logger.error(exp); throw exp; catch(SQLException exp) logger.error(exp); throw exp;It can be noted here that; though the catch blocks are having the same exception handling code, it is difficult to create a common catch block to eliminate duplicate code because variable exp has different types in both of the catch block.
Java multi-catch - Handling more than one type of exception
Java 7 onward it is possible to catch multiple exceptions in one catch block, which eliminates the duplicated code. Each exception type within the multi-catch statement is separated by Pipe symbol (|).
catch(IOException | SQLException exp) logger.error(exp); throw exp;Note that If a catch block handles more than one exception type, then the catch parameter is implicitly final. In this example, the catch parameter exp is final therefore you cannot assign any values to it within the catch block.
Java Multi-catch statement means better code
According to JavaDoc - "Bytecode generated by compiling a catch block that handles multiple exception types will be smaller (and thus superior) than compiling many catch blocks that handle only one exception type each. A catch block that handles multiple exception types creates no duplication in the bytecode generated by the compiler; the bytecode has no replication of exception handlers."
Multi-catch statement & Exception hierarchy
Specifying two or more exceptions of the same hierarchy in the multi-catch statement will result in compile time error.
As example- Following catch statement will give compiler error because FileNotFoundException is a subtype of the IOException class.
Or the following statement, which will also result in compile time error as Exception is super type of both ArithmeticException and ArrayIndexOutOfBoundsException.
// This will give compiler error catch(Exception | ArithmeticException | ArrayIndexOutOfBoundsException ex) ex.printStackTrace();Points to note
With multi-catch statement in Java it is possible to catch multiple exceptions in one catch block, which eliminates the duplicated code.Each exception type within the multi-catch statement is separated by Pipe symbol (|).Bytecode generated by compiling a catch block that handles multiple exception types will be smaller (and thus superior) than compiling many catch blocks that handle only one exception type each.Specifying two or more exceptions of the same hierarchy in the multi-catch statement will result in compile time error.Recommendations for learning
Java Programming Masterclass CourseJava In-Depth: Become a Complete Java Engineer!Spring Framework Master Class CourseComplete Python Bootcamp CoursePython for Data Science and Machine LearningReference: ://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html
That's all for this topic Multi-Catch Statement in Java Exception Handling. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Before Java 7, we had to write multiple exception handling codes for different types of exceptions even if there was code redundancy.
Let’s take an example.
Example 1: Multiple catch blocks
class Main public static void main(String[] args) try int array[] = new int[10]; array[10] = 30 / 0; catch (ArithmeticException e) System.out.println(e.getMessage()); catch (ArrayIndexOutOfBoundsException e) System.out.println(e.getMessage());Output
/ by zeroIn this example, two exceptions may occur:
- ArithmeticException because we are trying to divide a number by 0./ by zero
0 because we have declared a new integer array with array bounds 0 to 9 and we are trying to assign a value to index 10.
We are printing out the exception message in both the
/ by zero 1 blocks i.e. duplicate code.The associativity of the assignment operator
/ by zero 2 is right to left, so an ArithmeticException is thrown first with the message / by zero.In Java SE 7 and later, we can now catch more than one type of exception in a single
/ by zero 1 block.Each exception type that can be handled by the
/ by zero 1 block is separated using a vertical bar or pipe / by zero 6.Its syntax is:
try // code catch (ExceptionType1 | Exceptiontype2 ex) // catch blockExample 2: Multi-catch block
class Main public static void main(String[] args) ArrayIndexOutOfBoundsException e) System.out.println(e.getMessage());Output
/ by zeroCatching multiple exceptions in a single
/ by zero 1 block reduces code duplication and increases efficiency.The bytecode generated while compiling this program will be smaller than the program having multiple
/ by zero 1 blocks as there is no code redundancy.Note: If a
/ by zero 1 block handles multiple exceptions, the catch parameter is implicitly try // code catch (ExceptionType1 | Exceptiontype2 ex) // catch block 0. This means we cannot assign any values to catch parameters.Catching base Exception
When catching multiple exceptions in a single
/ by zero 1 block, the rule is generalized to specialized.This means that if there is a hierarchy of exceptions in the
/ by zero 1 block, we can catch the base exception only instead of catching multiple specialized exceptions.Let’s take an example.
Example 3: Catching base exception class only
class Main public static void main(String[] args) try int array[] = new int[10]; array[10] = 30 / 0; catch (Exception e) System.out.println(e.getMessage());Output
/ by zeroWe know that all the exception classes are subclasses of the
try // code catch (ExceptionType1 | Exceptiontype2 ex) // catch block 3 class. So, instead of catching multiple specialized exceptions, we can simply catch the try // code catch (ExceptionType1 | Exceptiontype2 ex) // catch block 3 class.If the base exception class has already been specified in the
/ by zero 1 block, do not use child exception classes in the same / by zero 1 block. Otherwise, we will get a compilation error.Let’s take an example.
Example 4: Catching base and child exception classes
class Main public static void main(String[] args) ArrayIndexOutOfBoundsException e) System.out.println(e.getMessage());Output
Main.java:6: error: Alternatives in a multi-catch statement cannot be related by subclassingIn this example, ArithmeticException and
/ by zero 0 are both subclasses of the try // code catch (ExceptionType1 | Exceptiontype2 ex) // catch block 3 class. So, we get a compilation error.