logo

Java Catch Multiple Exceptions

Блок Java Multi-catch

Блок try може супроводжуватися одним або кількома блоками catch. Кожен блок catch повинен містити інший обробник винятків. Отже, якщо вам потрібно виконувати різні завдання при виникненні різних винятків, використовуйте блок java multi-catch.

Пункти, які слід пам’ятати

  • Одночасно виникає лише один виняток і одночасно виконується лише один блок catch.
  • Усі блоки catch мають бути впорядковані від найбільш конкретного до найбільш загального, тобто catch для ArithmeticException має бути перед catch для Exception.

Блок-схема блоку Multi-catch

Java Catch Multiple Exceptions

Приклад 1

Давайте розглянемо простий приклад блоку java multi-catch.

MultipleCatchBlock1.java

 public class MultipleCatchBlock1 { public static void main(String[] args) { try{ int a[]=new int[5]; a[5]=30/0; } catch(ArithmeticException e) { System.out.println('Arithmetic Exception occurs'); } catch(ArrayIndexOutOfBoundsException e) { System.out.println('ArrayIndexOutOfBounds Exception occurs'); } catch(Exception e) { System.out.println('Parent Exception occurs'); } System.out.println('rest of the code'); } } 
Перевірте зараз

Вихід:

вимкнення режиму розробника
 Arithmetic Exception occurs rest of the code 

Приклад 2

MultipleCatchBlock2.java

 public class MultipleCatchBlock2 { public static void main(String[] args) { try{ int a[]=new int[5]; System.out.println(a[10]); } catch(ArithmeticException e) { System.out.println('Arithmetic Exception occurs'); } catch(ArrayIndexOutOfBoundsException e) { System.out.println('ArrayIndexOutOfBounds Exception occurs'); } catch(Exception e) { System.out.println('Parent Exception occurs'); } System.out.println('rest of the code'); } } 
Перевірте зараз

Вихід:

 ArrayIndexOutOfBounds Exception occurs rest of the code 

У цьому прикладі блок try містить два винятки. Але одночасно виникає лише один виняток і виконується відповідний йому блок catch.

MultipleCatchBlock3.java

 public class MultipleCatchBlock3 { public static void main(String[] args) { try{ int a[]=new int[5]; a[5]=30/0; System.out.println(a[10]); } catch(ArithmeticException e) { System.out.println('Arithmetic Exception occurs'); } catch(ArrayIndexOutOfBoundsException e) { System.out.println('ArrayIndexOutOfBounds Exception occurs'); } catch(Exception e) { System.out.println('Parent Exception occurs'); } System.out.println('rest of the code'); } } 
Перевірте зараз

Вихід:

 Arithmetic Exception occurs rest of the code 

Приклад 4

У цьому прикладі ми генеруємо NullPointerException, але не надаємо відповідний тип винятку. У такому випадку блок catch містить батьківський клас винятків Виняток буде викликано.

MultipleCatchBlock4.java

лисиця чи вовк
 public class MultipleCatchBlock4 { public static void main(String[] args) { try{ String s=null; System.out.println(s.length()); } catch(ArithmeticException e) { System.out.println('Arithmetic Exception occurs'); } catch(ArrayIndexOutOfBoundsException e) { System.out.println('ArrayIndexOutOfBounds Exception occurs'); } catch(Exception e) { System.out.println('Parent Exception occurs'); } System.out.println('rest of the code'); } } 
Перевірте зараз

Вихід:

 Parent Exception occurs rest of the code 

Приклад 5

Давайте розглянемо приклад обробки винятків без збереження порядку винятків (тобто від найбільш специфічних до найбільш загальних).

MultipleCatchBlock5.java

 class MultipleCatchBlock5{ public static void main(String args[]){ try{ int a[]=new int[5]; a[5]=30/0; } catch(Exception e){System.out.println('common task completed');} catch(ArithmeticException e){System.out.println('task1 is completed');} catch(ArrayIndexOutOfBoundsException e){System.out.println('task 2 completed');} System.out.println('rest of the code...'); } } 
Перевірте зараз

Вихід:

 Compile-time error