try { //Protected code }catch(ExceptionType1 e1) { //Catch block }catch(ExceptionType2 e2) { //Catch block }catch(ExceptionType3 e3) { //Catch block }
The previous statements demonstrate three catch blocks, but you can have any number of them after a single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack.
Lets see an example given below which shows the implementation of multiple catch blocks for a single try block.
public class MultiCatchBlock { public static void main (String args[]) { int array[] = {20,10,30}; int num1 = 15,num2 = 0; int res = 0; try { res = num1/num2; System.out.println("The result is" +res); for(int ct =2;ct >=0; ct--) { System.out.println("The value of array are" +array[ct]); } } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Error?. Array is out of Bounds"); } catch (ArithmeticException e) { System.out.println ("Can't be divided by Zero"); } } }
Output of the program:
In this example we have used two catch clause catching the exception ArrayIndexOutOfBoundsException and ArithmeticException in which the statements that may raise exception are kept under the try block. When the program is executed, an exception will be raised. Now that time the first catch block is skipped and the second catch block handles the error.
public class MultiCatchBlock { public static void main (String args[]) { int array[] = {20,10,30}; int num1 = 15,num2 = 0; int res = 0; try { res = num1/num2; System.out.println("The result is" +res); for(int ct =2;ct >=0; ct--) { System.out.println("The value of array are" +array[ct]); } } catch (Exception e) { System.out.println("Common Exception completed"); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Error?. Array is out of Bounds"); } catch (ArithmeticException e) { System.out.println ("Can't be divided by Zero"); } } }
Output:
Compile-time error
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…