Computer Science
Java Multiple Catch Blocks
Java Multiple Catch Blocks allow programmers to handle different types of exceptions in separate catch blocks. This feature enables the program to handle exceptions more efficiently and provide more specific error messages to the user. By using multiple catch blocks, the program can handle exceptions more gracefully and continue to execute the remaining code.
Written by Perlego with AI-assistance
Related key terms
1 of 5
10 Key excerpts on "Java Multiple Catch Blocks"
- No longer available |Learn more
Programming Fundamentals Using JAVA
A Game Application Approach
- William McAllister, S. Jane Fritz(Authors)
- 2021(Publication Date)
- Mercury Learning and Information(Publisher)
catch block must be included in the construct.Figure 10.2Syntax of the try-catch construct.The first line of each catch block includes a single parameter that is a reference to an exception object. Its type must be Throwable or a descendent of that class. When multiple catch blocks are included in the construct, each block must contain a different parameter type.The execution path of the try-catch construct is shown in Figure 10.3 . The statements in the try block are executed until one of them causes an exception, at which point the execution of the try block statement terminates, and the statements in the catch block whose parameter matches the type of the thrown exception object begins execution.Figure 10.3The execution path of the try-catch construct.NOTEA thrown exception object can be caught by a catch block whose parameter type is a direct or indirect super class of the thrown exception type.After the statements in the catch block complete their execution, the statements that follow the catch blocks begin execution. If the type of the thrown exception object does not match any of the parameter types in the catch blocks, and it is an unchecked exception, the statements that follow the catch blocks are executed. If an uncaught exception is a checked exception, the method terminates.Figure 10.4 presents the application ProcessingExceptions that calculates the quotient and remainder of two input numbers and gives the user three opportunities to correct the erroneous input of a zero divisor. The for - eBook - PDF
Microsoft® Visual C# 2015
An Introduction to Object-Oriented Programming
- Joyce Farrell, , , (Authors)
- 2015(Publication Date)
- Cengage Learning EMEA(Publisher)
They say that if you cannot predict all possible causes of an exception, you should allow the application to terminate instead of handling the exception. Otherwise, it is easier for malicious code to exploit the resulting application state. However, many professional programmers disagree with this policy. Although a block of code can throw any number of exceptions, many developers believe that it is poor style for a block or method to throw more than three or four types. If it does, one of the following conditions might be true: • Perhaps the code block or method is trying to accomplish too many diverse tasks and should be broken up into smaller blocks or methods. • Perhaps the Exception types thrown are too specific and should be generalized, as they are in the TwoErrors3 program in Figure 11-17. When you list multiple catch blocks following a try block, you must be careful that some catch blocks don’t become unreachable. Unreachable blocks contain statements that can never execute under any circumstances because the program logic “can’t get there.” Programmers also call unreachable code dead code . For example, if successive catch blocks catch an Exception followed by a DivideByZeroException , then even DivideByZeroExceptions will be caught by the Exception catch . The second, DivideByZeroException catch block is unreachable because the more general Exception catch block is in its way, and therefore the class will not compile. Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. 511 Catching Multiple Exceptions TWO TRUTHS & A LIE Catching Multiple Exceptions 1. - eBook - PDF
C# Programming
From Problem Analysis to Program Design
- Barbara Doyle, , , (Authors)
- 2015(Publication Date)
- Cengage Learning EMEA(Publisher)
. . catch . . . finally blocks. The code that might create a problem is placed in the try block. The code to deal with the problem (the exception handler) is placed in catch blocks, which are also called catch clauses . The code that you want executed regardless of whether an exception is thrown is placed in the finally block. The syntax for a try . . . catch . . . finally block is as follows: try { // Statements that might create a problem } catch [(ExceptionClassName exceptionIdentifier)] { // Exception handler statements } : // [additional catch clauses] [ finally { // Statements to be performed no matter what happens }] More than one catch clause can be included. A try block must include at least one catch clause. Notice that a square bracket follows the keyword catch to indicate that the parentheses and the argument list are optional. Omitting the argument list makes Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. Exception-Handling Techniques | 805 1 2 the catch generic —meaning any exception that is thrown is handled by executing the code within that catch block. If you include an exception type as part of the argu-ment list, only exceptions that match the type listed are handled by that catch clause. You will see examples using multiple catch clauses later in this chapter. The finally clause is also optional. It can be included if there is a segment of code that needs to be executed, no matter what. - Joyce Farrell(Author)
- 2012(Publication Date)
- Cengage Learning EMEA(Publisher)
In that case, you could place a statement such as the following in the catch block: output mistake.getMessage() The message generated by this built-in method would be similar to / by zero . As you will recall from the Java example in Figure 10-2, this message is generated when exception handling occurs automatically. Watch the video Throwing and Catching an Exception . Throwing and Catching Multiple Exceptions You can place as many statements as you need within a try block, and you can catch as many exceptions as you want. If you try more than one statement, only the first error-generating statement throws an exception. As soon as the exception occurs, logical control is transferred to the catch block, and the remaining statements in the try block are not executed. When a program contains multiple catch blocks, they are examined in sequence until a match is found for the type of exception that occurred. Then, the matching catch block executes and each remaining catch block is bypassed. For example, consider the application in Figure 10-6. The main() method in the TwoMistakes class throws two types of exceptions: ArithmeticException s and IndexOutOfBoundsException s. (An IndexOutOfBoundsException occurs when an array subscript is not within the allowed range.) 376 C H A P T E R 1 0 Exception Handling Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. In some programming languages, notably C++, exceeding an array ’ s bounds is not an exception. That is, the programmer can access memory outside of the array, even though it is a logical error.- eBook - ePub
- Prof. Sham Tickoo(Author)
- 2017(Publication Date)
- CADCIM Technologies(Publisher)
catch block.Example 2The following example illustrates the implementation of multiple catch blocks The program will divide a number and display the elements of an array on the screen.//Write a program to illustrate the implementation of multiple catch blocks 1class multi_catch_demo 2{3 public static void main(String arg[])4 {5 int num=10;6 int a = arg.length;7 int ar[ ] = {12, 23, 35, 46, 78};8 try9 {10 int result = num/a;11 System.out.println(“After division, the result is: ” +result);12 for(int i=0; i<=5; i++)13 {14 System.out.println(“Value at ar[”+i+“] is: ”+ar[i]);15 }16 }17 catch(ArrayIndexOutOfBoundsException e)18 {19 System.out.println(“An exception ” +e+ “ occurred”);20 }21 catch(ArithmeticException e)22 {23 System.out.println(“An exception ” +e+ “ occurred”);24 }25 }26} Explanation Line 6 int a = arg.length;In this line, the length method will return the number of arguments that will be passed during the execution of the program. Next, the resultant value will be assigned to the integer type variable a .Line 7 int ar[ ] = {12, 23, 35, 46, 78};In this line, ar is declared as an integer type array. The values 12, 23, 35, 46, and 78 will be assigned to the elements of the array ar[ ] ; for example, value 12 will be assigned to ar[0] , 23 to ar[1] , and so on.Lines 8 to 16 try {int result = num/a;System.out.println(“After division, the result is: ” +result);for(int i=0; i<=5; i++){System.out.println(“Value at ar[”+i+“] is: ”+ar[i]);}}These lines contain the definition of the try block. Inside the try block, the value of num variable will be divided by the value of a variable and the resultant value will be assigned to the integer type variable result . If the value of a variable will be 0, the arithmetic exception / by zero will be generated and the remaining part of the try block will be skipped. Otherwise, the value of result variable will be displayed. Moreover, inside the body of the for loop, the values stored in the elements of the array ar[ ] will be displayed. Here, the for loop will generate the exception ArrayIndexOutOfBoundsException because an attempt will be made to access the sixth element which does not exist in the array ar[ ] - eBook - PDF
- Joyce Farrell(Author)
- 2018(Publication Date)
- Cengage Learning EMEA(Publisher)
Figure 12-21 Several executions of the DivisionMistakeCaught4 application Watch the video Catching Multiple Exceptions. The false statement is #1. If you try more than one statement, only the first error- generating statement throws an exception, and then the rest of the try block is abandoned. TWO TRUTHS & A LIE Throwing and Catching Multiple Exceptions 1. When multiple try block statements throw exceptions, multiple catch blocks might execute. 2. As soon as an exception occurs, the try block that contains it is abandoned and the rest of its statements are unexecuted. 3. When a program contains multiple catch blocks, the first one that matches the thrown Exception type is the one that executes. Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. 590 Exception Handling C H A P T E R 1 2 Using Multiple catch Blocks In this section, you add a second catch block to the ExceptionDemo application. 1. Open the ExceptionDemo.java file. Change the class name to ExceptionDemo2, and save the file as ExceptionDemo2.java. 2. Execute the program, and enter a noninteger value at one of the prompts. Program execution fails. For example, Figure 12-22 shows the error generated when the user types a string at the first prompt. 3. After the existing catch block that catches an ArithmeticException object, add a catch block that catches a NumberFormatException object if neither user entry can be converted to an integer. If this block executes, display an error message, set numerator and denominator to a default value of 999, and force result to 1. - eBook - PDF
- Ivor Horton(Author)
- 2005(Publication Date)
- Wrox(Publisher)
Loop entered i = 12 j = 3 4 Loop entered i = 12 j = 2 6 Loop entered i = 12 j = 1 12 Loop entered i = 12 j = 0 Arithmetic exception caught After try block Now, you no longer get the output for the last iteration because control passes to the catch block when the exception is thrown, and that is now outside the loop. Multiple catch Blocks If a try block can throw several different kinds of exception, you can put several catch blocks after the try block to handle them: try { // Code that may throw exceptions } catch(ArithmeticException e) { // Code for handling ArithmeticException exceptions } catch(IndexOutOfBoundsException e) { // Code for handling IndexOutOfBoundsException exceptions } // Execution continues here... Exceptions of type ArithmeticException will be caught by the first catch block, and exceptions of type IndexOutOfBoundsException will be caught by the second. Of course, if an ArithmeticException exception is thrown, only the code in that catch block will be executed. When it is complete, execution continues with the statement following the last catch block. 349 Exceptions When you need to catch exceptions of several different types that may be thrown in a try block, the order of the catch blocks can be important. When an exception is thrown, it will be caught by the first catch block that has a parameter type that is the same as that of the exception, or a type that is a super- class of the type of the exception. An extreme case would be if you specified the catch block parameter as type Exception. This will catch any exception that is of type Exception, or of a class type that is derived from Exception. This includes virtually all the exceptions you are likely to meet in the normal course of events. This has implications for multiple catch blocks relating to exception class types in a hierarchy. The catch blocks must be in sequence with the most derived type first, and the most basic type last. - eBook - PDF
- Russel Winder, Graham Roberts(Authors)
- 2014(Publication Date)
- Wiley(Publisher)
A sequence of statements that may result in an exception being thrown when executed is wrapped in a try block, which is just a compound statement preceded by the keyword try . Associated with the try block are one or more catch blocks, which is a compound statement preceded by the keyword catch followed by the declaration of a variable of an exception type (subclass of Throwable) in parentheses. A catch block is a block with an exception type parameter specifying which type of exception object the block will catch. For example: try { anObject.f ( ) ; anotherObject.g ( ) ; } catch ( SomeException se ) { // do something to recover } catch ( SomeOtherException soe ) { 8.5 Catching Exceptions ! throw and throws are two distinct keywords. ! The catch block variables are all in the same scope and so must all have distinct names. ref See Chapter 23, page 787, for a detailed description of exceptions. 276 Chapter 8: Exceptions // do something to recover } The methods anObject.f and anotherObject.g may throw exceptions and so they are within a try block. The possible types exceptions that can be thrown are SomeException or SomeOtherException, so there are catch block associated with the try block for each of those types. The try block will be executed as part of the usual order of execution. If no exception is thrown then when the sequence is complete, control transfers to the statement following the whole try–catch block, i.e. all the catch blocks are ignored. If an exception is thrown the execution of the statement sequence in the try block stops immediately and an attempt is made to find an appropriate catch block to catch the exception. A search is made through all the catch blocks associated with the try block in the order they appear in the code to see if one of the catch blocks’ exception variables is of the same type or a supertype of the exception thrown. If a matching catch block is found then the statement sequence in that block is executed. - eBook - PDF
C++ Programming
From Problem Analysis to Program Design
- D. Malik(Author)
- 2017(Publication Date)
- Cengage Learning EMEA(Publisher)
6. The try block is followed by one or more catch blocks. 7. A catch block specifies the type of exception it can catch and contains an exception handler. Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. 1026 | Chapter 14: Exception Handling 8. If the heading of a catch block contains . . . (ellipsis) in place of param- eters, then this catch block can catch exceptions of all types. 9. If no exceptions are thrown in a try block, all catch blocks associated with that try block are ignored and program execution resumes after the last catch block. 10. If an exception is thrown in a try block, the remaining statements in the try block are ignored. The program searches the catch blocks, in the order they appear after the try block, and looks for an appropriate excep- tion handler. If the type of the thrown exception matches the parameter type in one of the catch blocks, then the code in that catch block executes and the remaining catch blocks after this catch block are ignored. 11. The data type of the catch block parameter specifies the type of exception that the catch block can catch. 12. A catch block can have, at most, one catch block parameter. 13. If only the data type is specified in a catch block heading, that is, if there is no catch block parameter, then the thrown value may not be accessible in the catch block exception-handling code. 14. In order for an exception to occur in a try block and be caught by a catch block, the exception must be thrown in the try block. - eBook - ePub
Beginning Java Programming
The Object-Oriented Approach
- Bart Baesens, Aimee Backiel, Seppe vanden Broucke(Authors)
- 2015(Publication Date)
- Wrox(Publisher)
It is impossible to cover every possible exception in this book, but with this foundation, you should be able to begin to deal with them appropriately. If you encounter other exceptions as you are programming, searching online for the name of the exception will help you understand why it is occurring. The techniques demonstrated in the next section will help you deal with all kinds of exceptions.Catching Exceptions
Now that you’ve been introduced to the three main error categories and some common exceptions, it’s time to start learning how to handle them when you do encounter them. The first step is a new structure called a try/catch block. This essentially allows you to try executing a piece of code to see if an exception is thrown. If none is thrown, the program will proceed normally, but if one is thrown, you can catch it and specifically indicate what should be done next. This prevents your program from crashing and at least allows you to recover some information before it terminates.The general form of a try/catch block looks like this:try { // execute some statements } catch (Exception exc){ // statements to handle the exception } finally { // no matter what, do this }NOTE While this book refers to these as try/catch blocks, there are in fact three separate components: try,catch, and finally blocks. You may encounter any of the following: a try block with (one or more) catch blocks; a try block with (one or more) catch blocks and a finally block; or, less commonly, a try block with only a finally block.Now you can see how they are used by looking again at the retirement fund examples. Recall how you got a division by zero exception when you tried to divide an int retirementFund by another int yearsInRetirement
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.









