Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java

Students frequently turn to Computer Class 12 GSEB Solutions and GSEB Computer Textbook Solutions Class 12 Chapter 9 Working with Array and String for practice and self-assessment.

GSEB Computer Textbook Solutions Class 12 Chapter 9 Working with Array and String

Question 1.
What is the difference between compile-time error and run-time error ?
Answer:

  • In Java, all kinds of error conditions are called exceptions.
  • Errors can be broadly classified into two categories namely:
    1. Compile-time errors
    2. Run-time errors

(1) Compile-time errors

  • A compiler is used to convert source code into object code.
  • If there is a syntax error in the program, a compilation error is displayed and “.class” file is not created.
  • Examples of some common syntax errors are missing like a semicolon, use of undeclared variable, wrong spellings of identifier or keyword and mismatch of bracket.
  • The java program shown in figure does not contain a semicolon.

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 1

  • The above code when compiled generates a compile-time error because the semicolon is missing in line number 8.
  • The Java compiler suggests in the output, the type of error, along with the line number where the error has occurred as shown in figure.

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 2

 

  • Compile-time errors are usually the mistakes of a programmer and it does not allow the program to compile unless they are solved.
  • Note : In the field of Computer Science, “Exit code” or “Exit status” indicates whether the command or a program executed successfully or not.
  • Code “0” indicates that the command executed successfully whereas code “1” indicates that some problem occurred while executing the command. In figure, the last line indicates “Exit Code: 1”, it means that the compilation of program – ErrorDemo.java was not successful.

(2) Run-time Errors :

  • If there are no syntax errors in the source code then the program will compile successfully and will get a “.class” file. ’ “
  • However this does not guarantee that the program will execute as per the expectations.
  • Figure is another example which will compile but will terminate abnormally.

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 3

  • The program shown in figure compiles as there are no syntax errors in it.
  • In the program, there is an array “citylist [ ]” that contains name of four different cities.
  • In line 14, the program displays the content of element of citylist array that does not exist.
  • This is a case of an exception condition.
  • The exception will be generated during runtime.
  • The output of the execution of the program is shown in figure.

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 4

 

  • From the output shown in figure, one can notice that the program execution terminated abruptly from line number 14.
  • The output contains a phrase “ArraylndexOutOfBoundsException” that indicates the type of exception occurred while executing the program.
  • Below given are few other cases that generate exceptions.
  • For each type of exception, there are corresponding Exceptions classes in Java.
  • The java.lang and java.io package contains a hierarchy of classes dealing with various exceptions.
  • Few widely observed exceptions are listed in Table 10.1.
Exception Class Condition resulting in Exception Example
ArraylndexOutOfBoundsException An attempt to access the array element with an index value that is outside the range of array int a[ ] = new int[4]; a[13] = 99;
ArithmeticException An attempt to divide any number by 0 int a = 50 / 0;
FileNotFoundException An attempt to access a non­existing file
NullPointerException An attempt to use null in a case where an object is required String s = null;

System.out.println(s.length());

NumberFormatException An attempt to convert string to a number type String s = “xyz”;

int i = Integer.parselnt(s);

PrinterlOException An I/O error has occurred while printing

Table : List of few widely observed Exceptions

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 5

  • Figure also shows a program which generates an exception. In this figure, the program tries to divide » an integer number by zero.
  • A number when divided by zero leads to infinity as a result. The program compiles successfully but generates unexpected output due to Arithmetic Exception.
  • Figure shows the output of the execution of program.

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 6

 

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java

Question 2.
What is an Exception ? Give examples of few exceptions found in Java.
Answer:

  • In Java, all kinds of error conditions are called exceptions.
  • Errors can be broadly classified into two categories namely:
    1. Compile-time errors
    2. Run-time errors

(1) Compile-time errors

  • A compiler is used to convert source code into object code.
  • If there is a syntax error in the program, a compilation error is displayed and “.class” file is not created.
  • Examples of some common syntax errors are missing like a semicolon, use of undeclared variable, wrong spellings of identifier or keyword and mismatch of bracket.
  • The java program shown in figure does not contain a semicolon.

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 1

  • The above code when compiled generates a compile-time error because the semicolon is missing in line number 8.
  • The Java compiler suggests in the output, the type of error, along with the line number where the error has occurred as shown in figure.

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 2

 

  • Compile-time errors are usually the mistakes of a programmer and it does not allow the program to compile unless they are solved.
  • Note : In the field of Computer Science, “Exit code” or “Exit status” indicates whether the command or a program executed successfully or not.
  • Code “0” indicates that the command executed successfully whereas code “1” indicates that some problem occurred while executing the command. In figure, the last line indicates “Exit Code: 1”, it means that the compilation of program – ErrorDemo.java was not successful.

(2) Run-time Errors :

  • If there are no syntax errors in the source code then the program will compile successfully and will get a “.class” file. ’ “
  • However this does not guarantee that the program will execute as per the expectations.
  • Figure is another example which will compile but will terminate abnormally.

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 3

  • The program shown in figure compiles as there are no syntax errors in it.
  • In the program, there is an array “citylist [ ]” that contains name of four different cities.
  • In line 14, the program displays the content of element of citylist array that does not exist.
  • This is a case of an exception condition.
  • The exception will be generated during runtime.
  • The output of the execution of the program is shown in figure.

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 4

 

  • From the output shown in figure, one can notice that the program execution terminated abruptly from line number 14.
  • The output contains a phrase “ArraylndexOutOfBoundsException” that indicates the type of exception occurred while executing the program.
  • Below given are few other cases that generate exceptions.
  • For each type of exception, there are corresponding Exceptions classes in Java.
  • The java.lang and java.io package contains a hierarchy of classes dealing with various exceptions.
  • Few widely observed exceptions are listed in Table 10.1.
Exception Class Condition resulting in Exception Example
ArraylndexOutOfBoundsException An attempt to access the array element with an index value that is outside the range of array int a[ ] = new int[4]; a[13] = 99;
ArithmeticException An attempt to divide any number by 0 int a = 50 / 0;
FileNotFoundException An attempt to access a non­existing file
NullPointerException An attempt to use null in a case where an object is required String s = null;

System.out.println(s.length());

NumberFormatException An attempt to convert string to a number type String s = “xyz”;

int i = Integer.parselnt(s);

PrinterlOException An I/O error has occurred while printing
  • Table 10.1 : List of few widely observed Exceptions
    Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 5
  • Figure also shows a program which generates an exception. In this figure, the program tries to divide » an integer number by zero.
  • A number when divided by zero leads to infinity as a result. The program compiles successfully but generates unexpected output due to Arithmetic Exception.
  • Figure shows the output of the execution of program.

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 6

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java

Question 3.
How are the exceptions handled in java ?
Answer:

  • An exception is an error condition. Exception handling is an object-oriented technique for managing errors.
  • While performing exception handling, one has to try to ensure that the program does not terminate abruptly nor does it generate unexpected output.
  • Java uses keywords like try, catch and finally to write an exception handler.
  • The keywords try, catch and finally are used in the presence of exceptions, these keywords represent block of statements.
  • A try block contains the code that may give rise to one or more exceptions.
  • A catch block contains the code that is intended to handle exceptions of a particular type that were created in the associated try block.
  • A finally block is always executed before the program ends, regardless of whether any exceptions are generated in the try block or not.

Question 4.
What is the significance of try, catch and finally block ?
Answer:
The try block :

  • The try statement contains a block of statements within the braces.
  • This is the code that has to be monitored for exceptions.
  • If a problem occurs during its execution, an exception is thrown.
  • Each type of problem (exception) corresponds to an object in Java.
  • A try block may give rise to one or more exceptions.
  • The syntax of the try block is given below :
try
{
// Set of statements that may generate one or more exceptions
}
  • As stated earlier, the code between a try block creates a single exception.
  • The code shown in figure, when executed will terminate the program as there is no exception handler.
  • The part of the program that may lead to runtime error must be written within the try block.

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 7

  • On compiling the program in figure, it results in compilation error as there has to be either a catch block or a finally block following the try block.
  • The compilation error is shown in figure.

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 8

 

The catch block :

  • The catch block must immediately follow the try block.
  • It contains the code that is to be created to handle an exception.
  • The catch block is an exception handler, for a single try block there can be one or more catch blocks.
  • The syntax of the catch block is given below:
try
{
//Set of statements that may generate one or more exceptions
}
catch (Exception_Type Exception_object)
{
//Code to handle the exception
}
  • A catch block consists of the keyword catch followed by a single parameter. The code to handle exception has to be written between parentheses.
  • The parameter identifies the type of exception that the block is to deal with.
  • Java supports various types of exceptions.
  • Figure illustrates mechanism of try-catch block.

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 9

  • Figure is an example program that uses appropriate exception handler.
  • The program handles Arraylndex Out Of Bounds exception by just catching the object within catch block.

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 10

  • The code shown in figure will compile successfully and execute.
  • In the program shown in figure, line 16 contains statement that will generate exception.
  • At line 16, the program tries to access the fifth element of an array citylist [ ], however the array contains only four members.
  • The program tries to access array element by specifying index position that is outside the range which leads to an exception.
  • When an exception occurs, an object of type Array Index Out Of Bounds Exception is created and is thrown.
  • A corresponding catch block handles the exception and does not allow the program to terminate unexpectedly.
  • The catch block contains a reference to object “eobj” which is created and thrown by the try block.
  • Figure shows the output of the program.

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 11

  • It can be observed from figure that the program did not terminate in the presence of exception.
  • The statement displaying “after try catch” gets executed.

Multiple catch blocks :

  • In a single program multiple exceptions can occur.
  • For instance, if a particular file has to be uploaded to a remote computer, it may lead to two distinct exceptions – an exception may occur if the file is not present in the computer or another exception may occur if the computer is not connected to the network.
  • There is a provision in Java to support multiple exceptions.
  • The code that generates exception should be written within the try block.
  • Apart from this there can be multiple catch blocks to handle each type of exception separately.

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 12

  • Figure shows where multiple catch blocks are used. Here two distinct exceptions are generated within the try block.
  • Exception of type Array Index Out Of Bounds Exception will be caught by the first catch block and -exception of type Arithmetic Exception will be caught by the second catch block.

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 13

  • The last catch block can handle any type of exception.
  • It is a kind of default catch block and must be the last block when there are multiple catch blocks.
  • While writing the program, the order of the specific catch blocks does not matter but the default block has to be placed at the end of all catch blocks.
  • For instance, in the program shown in the figure, the occurrence of the catch blocks can be swapped of catch block starting at line 18 with the one starting at line number 21.
  • However the catch block given at the line 24 must be the last block.
  • Multiple try blocks can be nested together, but care must be taken to write a corresponding catch block for each try block.

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java

The finally block :

  • The finally block is generally used to clean up the end of executing a try block.
  • A finally block is used when the programmer wants to be sure that some particular code is to be run, no matter what exceptions are thrown within the associated try block.
  • A finally block is always executed, regardless of whether or not exceptions are thrown during the execution of the associated try block.
  • A finally block is widely used if a file needs to be closed or a critical resource is to be released at the completion of the program.
  • The syntax of finally block is given below :
finally
{
//clean-up code to be executed last
//statements within this block always get
executed even though if run-time
errors terminate the program abruptly
}
  • Each try block must always be followed by at least one block that is either a catch block or a finally block.
  • Figure shows an example of using finally block.

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 14

  • In the program shown in figure, there is no catch block, so the program terminates abruptly due to the exception generated at line 14.
  • Statements present in line 15 and line 16 are not executed.
  • However, in the presence of finally block, the program executes the statements within the finally block before it gets terminated.
  • The output of the program is shown in figure.

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 15

  • An example with multiple catch blocks and a finally block all used together is shown in figure.
  • It is a complete program with multiple catch blocks for corresponding exceptions being generated within the try block. Output of program is shown in figure.

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 16

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 17

  • From the above output, it is clear that the control of program execution switched from line 11 to the first catch block, later it switched to the finally block.
  • The last two catch blocks did not execute.
  • Although the program did not execute completely, it terminated gracefully.
  • A finally block is associated with a particular try block, and it must be located immediately following any catch blocks for the corresponding try block.
  • If there are no catch blocks, then the finally block can be positioned immediately after the tty block.
  • If the finally block or catch blocks are not positioned correctly, then the program will not compile.

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java

Question 5.
What is the use of throw and throws keyword ?
Answer:
The throw statement :

  • The throw keyword is used to explicitly throw an Exception object.
  • In the example programs that have been done so far, the JVM created an exception object and was throwing it automatically.
  • For example, an object of ArithmeticException was created when one tries to perform a divide by zero operation and it is thrown automatically by the JVM.
  • Java does provide mechanism to create an Exception object and throw it explicitly.
  • The object that one throws, must be of type java.lang.Throwable, (object of Throwable class or any of its sub-classes) otherwise a compile error occurs.
  • The syntax to throw an exception object is as follows :
    throw exception_object;
  • When a throw statement is encountered, a search for matching catch block begins.
  • Any subsequent statements in the try or catch block are not executed.
  • The code in figure shows the used of throw statement, its output is given in figure.

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 18

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 19

  • In the program shown in figure, an object “obj” has been created of the class Exception and the same object is thrown using throw statement.
  • There has to be catch blocks to handle the exception object thrown explicitly.

The throws clause :

  • There are two alternative approaches to handle, when an exception occurs in a method or a constructor.
    1. Write a try-catch block within the method or a constructor that may generate an exception.
    2. Invoking a method (that may generate exception) or constructor within a try block.
  • A throws clause can be used in a method declaration or constructor declaration to inform that the code within the constructor or method may throw an exception.
  • It also signifies that there is no catch block within the method that can handle the exception.
  • When a constructor or a method that can throw exceptions is written to its caller, it is useful to document that fact. The throws keyword is used with the declaration of method.
  • A throws clause can be used in a method declaration as follows :
method_Modifiers returntype
method_Name(parameters) throws) throws
Exception list...
{
........
// body of the method
........
}
  • A method can throw multiple exceptions. Each type of exception that a method can throw must be stated in the method header. For example, a method header can be like :
perform Division() throws Arithmetic
Exception, Array Index Out Of Bounds
Exception.
{
..........
// body of the method
..........
}
  • The program in figure demonstrates the use of throws clause in the presence of user defined methods.

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 20

  • In the foiiowing code, it must he noted that if the method throws an Exception object, there must be a matching catch handler.
  • However, if an exception type has to be caught within the method, there is no need to throw it.
  • In the program of figure, there is a method perform Division(). An Arithmetic Exception object will be generated in this method.
  • The method performDivision( ) is called in the main( ) method of the program.
  • There is no exception-handling mechanism within the performDivision( ) method, the exception will be caught by calling method and there has to be a handler in the calling method.
  • Similarly, there can be exceptions within the Constructors of Java class.

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java

Question 6.
How do you create a custom exception ?
Answer:
creating a custom exceptions

  • Java allows creating own exception classes according to application-specific problems.
  • For instance, in a program which generates a mark sheet, the user is asked to enter marks of different subjects.
  • The marks must be in the range of 0 to 100.
  • Suppose the user enters negative marks or the value which is above 100, then the program must generate an Exception.
  • Such kinds of exceptions are application specific.
  • Java does not provide built-in exception classes for application specific exceptions.
  • User-defined exceptions can be created by creating a subclass of Exception class.
  • These Exceptions can be thrown explicitly using throws statement.
  • However, it is required to catch this exception and handle it accordingly.
  • The program shown in figure accepts input from the user.
  • In the program java.util.Scanner class is used to accept input from the keyboard in line number 21.
  • The “nextInt( )” method of the Scanner class helps in reading integer from the console.
  • The program of figure has implemented two classes.
  • An additional class is required to create a custom exception.
  • The class “Invalid Marks Exception” extends Exception class of java.lang package.
  • It contains a single parameter constructor that accepts string to describe the type of error.
  • In the main method, the business logic is coded (application specific) that ensures whether the marks are in range or not.
  • If the marks are not in range, an object of type “Invalid Marks Exception” is created and thrown.

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 21

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 22

  • There has to be a catch block to handle this exception.
  • This program will not proceed unless valid marks are entered. In case, if the user enters invalid marks, he/she will be asked to keep on re-entering until the input is correct.
  • It must be noted that try-catch blocks are used with in a do-while loop.
  • The output is shown in figure.

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java 23

  • Note: SciTE is an editor to type the programs. If the program accepts data from the keyboard, it is advisable to execute the program at command prompt; however, a simple program that does not require user interaction can be executed from within SciTE editor.

Question 7.
Choose the most appropriate option from those given below:

1) Which of the following refers to an error condition in object-oriented programming terminology ?
(A) Anomaly
(B) Abbreviation
(C) Exception
(D) Deviation
Answer:
(C) Exception

2) Which of the following is a correct word for all Java Exceptions ?
(A) Errors
(B) Runtime Exceptions
(C) Throwables
(D) Omissions
Answer:
(B) Runtime Exceptions

3) Which of the following statements is true ?
(A) Exceptions are more serious than Errors.
(B) Errors are more serious than Exceptions.
(C) Errors and Exceptions are equally serious.
(D) Exceptions and Errors are the same thing.
Answer:
(D) Exceptions and Errors are the same thing.

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java

4) Which of the following elements is not included in try block ?
(A) The keyword try
(B) The keyword catch
(C) The curly braces
(D) Statements that might cause Exceptions
Answer:
(B) The keyword catch

5) Which of the following block handles or takes appropriate action when an Exception occurs ?
(A) Try
(B) Catch
(C) Throws
(D) Handles
Answer:
(B) Catch

6) Which of the following should be within a catch block ?
(A) Finally block
(B) Single statement that handles Exception
(C) Any number of statements to handle Exception
(D) Throws keyword
Answer:
(C) Any number of statements to handle Exception

7) What will happen when a try block does not generate an Exception and you have included multiple catch blocks ?
(A) They all execute
(B) Only the first matching one excecutes
(C) No catch block executes
(D) Only the first catch block executes
Answer:
(C) No catch block executes

8) Which of the following is an advantage of using a try….catch block ?
(A) Exceptional events are eliminated
(B) Exceptional events are reduced
(C) Exceptional events are integrated with regular events
(D) Exceptional events are isolated from regular events
Answer:
(C) Exceptional events are integrated with regular events

9) Which of the following methods can throw an Exception ?
(A) Methods with throws clause
(B) Methods with a catch block
(C) Methods with a try block
(D) Methods with finally block
Answer:
(C) Methods with a try block

10) Which of the following is least important to know if you want to be able to use a method to its full potential ?
(A) The method’s return type
(B) The type of arguments the method requires
(C) The number of statements within the method
(D) The type of Exceptions the method throws
Answer:
(C) The number of statements within the method

Computer Class 12 GSEB Solutions Chapter 10 Exception Handling in Java

Computer Class 12 GSEB Notes Chapter 10 Exception Handling in Java

Advantages of Exception Handling

  • A good program must always handle exceptions rather than the program being terminated abruptly.
  • Few advantages of using exception-handling in Java programs are listed below :
    1. It allows maintaining normal flow of program. In the absence of exception handling, the flow of program is disturbed.
    2. It allows writing separate error handling code from the normal code.
    3. Error types can be grouped and differentiated within the program.
    4. Assertions can be used to debug the program before deploying it to the clients.
    5. It provides an easy mechanism to log various run-time errors while executing the program.

Leave a Comment

Your email address will not be published. Required fields are marked *