Teachnique
      CourseRoadmaps
      Login

      OverviewHistoryFeaturesJava 8 - New Featuresvs C++Virtual Machine(JVM)JDK vs JRE vs JVMHello World ProgramEnvironment SetupBasic SyntaxVariable TypesData TypesType CastingUnicode SystemBasic OperatorsCommentsStreamsNew Date-Time API

      Loop ControlDecision Makingif-else Statementswitch statementfor loopfor each Loopwhile Loopdo...while Loopbreak Statementcontinue Statement

      OOPs (Object-Oriented Programming) ConceptsObject and ClassesClass AttributesClass MethodsMethodsVariable ScopesConstructorsAccess ModifiersInheritanceAggregationPolymorphismOverridingMethod OverloadingDynamic BindingStatic BindingInstance Initializer BlockAbstractionEncapsulationInterfacesPackagesInner classesStatic ClassesAnonymous ClassesSingleton ClassWrapper ClassesEnum Class

      Number ClassBoolean classCharacter ClassArraysMath Class

      File ClassCreating FilesWrite To FilesReading FileDelete FilesDirectory OperationsFiles and I/O

      ExceptionsTry Catch BlockTry with ResourcesMultiple Catch BlocksNested Try BlockFinally BlockThrows and Throw | Throw an ExceptionException PropagationBuilt-in ExceptionsCustom Exception

      MultithreadingThread Life CycleCreating a ThreadStarting a ThreadJoining ThreadsNaming a Thread with ExamplesScheduling Threads with ExamplesThread PoolsMain ThreadThread PriorityDaemon ThreadThreadGroup ClassJVM Shutdown Hook

      Thread SynchronizationBlock SynchronizationStatic SynchronizationInter Thread CommunicationThread DeadlockInterrupting ThreadThread ControlReentrant Monitor

      NetworkingSocket ProgrammingURL ProcessingURL ClassURLConnection ClassHttpURLConnection ClassSocket Class with ExamplesGenerics

      Collections FrameworkCollection Interface

      List InterfaceArrayList Class

      Queue InterfaceArrayDeque Class

      Map InterfaceSortedMap Interface

      Set InterfaceSortedSet Interface

      Data Structures Enumeration Interface BitSet Class

      How to Use Iterator?How to Use Comparator?How to Use Comparable?

      RecursionRegular ExpressionsSerializationString ClassJava Arrays - Class

      Feedback

      Submit request if you have any questions.

      Course
      Multiple Catch Blocks

      Java Tutorial

      This Java tutorial is tailored for newcomers, offering a journey from basic principles to complex Java programming techniques. Completing this tutorial equips you with a solid understanding of Java, preparing you for advanced learning. You'll emerge ready to tackle the challenges of becoming a top-tier software engineer, with the skills to innovate and excel in the vast world of software development.

      Multiple Catch Blocks

      Multiple Catch Blocks in Java

      Multiple catch blocks in Java are used to catch/handle multiple exceptions that may be thrown from a particular code section. A try block can have multiple catch blocks to handle multiple exceptions.

      Syntax: Multiple Catch Blocks

      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.

      Points to Remember while using Multiple Catch Blocks

      • Only one type of exception can be handled at a time. In protected, only one type of exception will be raised, so it will be handled in relevant catch block only.
      • Order of catch block is very important. Order should be from specific exception to generic one. In case of parent exception block comes before the child exception block, compiler will complain and will throw compile time error.

      Example of Java Multiple Catch Blocks

      Here is code segment showing how to use multiple try/catch statements. In this example, we're creating an error by dividing a value by 0. As it is not an ArrayIndexOutOfBoundsException, next catch block handles the exception and prints the details.
      package com.tutorialspoint;
      
      public class ExcepTest {
      
      public static void main(String args[]) {
      try {
      int a[] = new int[2];
      int b = 0;
      int c = 1/b;
      System.out.println("Access element three :" + a[3]);
      }
      catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("ArrayIndexOutOfBoundsException thrown :" + e);
      }catch (Exception e) {
      System.out.println("Exception thrown :" + e);
      }
      System.out.println("Out of the block");
      }
      }

      Output

      Exception thrown :java.lang.ArithmeticException: / by zero
      Out of the block

      Handling Multiple Exceptions Using Multiple Catch Blocks

      In this code segment, we're showing how to use another example of multiple try/catch statements. In this example, we're creating an error by dividing a value by 0 and handling it using ArithmeticException.

      Example

      package com.tutorialspoint;
      
      public class ExcepTest {
      
      public static void main(String args[]) {
      try {
      int a[] = new int[2];
      int b = 0;
      int c = 1/b;
      System.out.println("Access element three :" + a[3]);
      }
      catch (ArithmeticException e) {
      System.out.println("ArithmeticException thrown :" + e);
      }
      catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("ArrayIndexOutOfBoundsException thrown :" + e);
      }catch (Exception e) {
      System.out.println("Exception thrown :" + e);
      }
      System.out.println("Out of the block");
      }
      }

      Output

      ArithmeticException thrown :java.lang.ArithmeticException: / by zero
      Out of the block

      Handling Multiple Exceptions Within A Single Catch Block

      Since Java 7, you can handle more than one exception using a single catch block, this feature simplifies the code. Here is how you would do it

      Syntax

      catch (IOException|FileNotFoundException ex) {
      logger.log(ex);
      throw ex;

      Example

      Here is code segment showing how to use multiple catch in a single statement. In this example, we're creating an error by dividing a value by 0. In single statement, we're handling ArrayIndexOutOfBoundsException and ArithmeticException.
      package com.tutorialspoint;
      
      public class ExcepTest {
      
      public static void main(String args[]) {
      try {
      int a[] = new int[2];
      int b = 0;
      int c = 1/b;
      System.out.println("Access element three :" + a[3]);
      }
      catch (ArrayIndexOutOfBoundsException | ArithmeticException e) {
      System.out.println("Exception thrown :" + e);
      }
      System.out.println("Out of the block");
      }
      }

      Output

      Exception thrown :java.lang.ArithmeticException: / by zero
      Out of the block