Exceptions 247
Managing Errors and
public
static void main (String| args)
(BufferedRe-ader br = hew BufferedReader(now Fi leReader( C :
try
TWR. txt ")))
String stI;
// Perform I0 operat ions
need to eXplicitly close the resource
catch (1OEXCeption e)
NO need for finally block
End of main
End of class
13.9
USING EXCEPTIONS FOR DEBUGGING
bave seen, the exception-handling mechanism can be used to hide errors from rather
rest ofthan
the
program. It is pOssible that the programmers may misuse this technique for hiding errorsthe type and
debugging the code. EXception handling mechanism may be effectively used to locate
e errors. Once we identify the errors, we must try to find out why these errors occur before we
handlers
cover them up with exception
SUMMARY
A000d program does not produce unexpected results. We should incorporate features that could
check for potential problem spots in programs and guard against program failures. The problem
onditions known as exceptions in Java must be handled carefully to avoid any program failures.
In this chapter we have discussed the following:
" What are exceptions
How to throw system exceptions
Howto define our own exceptions
Howto catch and handle different types of exceptions
" Where to use exception handling tOols
We must ensure that common exceptions are handled where appropriate.
REVIEW QUESTIONS
13.1 What is an exception? 2 marks
13.2 How do we define atry block? 2 marks
13.3 How do we define a catch block? 2 marks
134 List some of the most common types of exceptions that might occur in Java. Give examples. 5 marks
2 marks
s it essential to catch all types of exceptions?
13.6 How many catch blocks can we use with one try block? 2 marks
13.7 Create a try block that is likely to generate three types of exception and then
necessary catch blocks to catch and handle them appropriately. 10 marks incorporate
o What is a finally block? When and how is it used? Give a suitable example. 5 marks
248
Programming with Java: APrimer
debugging a prn
EXplain how exception handling mechanism can be used for
O. when a 5marks
T3.10 Define an exception called "NoMatchException" that is thrown string is not
"India". Write a program that uses this exception. 5 marks
equa
DEBUGGING EXERCISES
13.1 The following code catches Arithmetic Exception. Willthis code work? If not. whv
5 marks
class excel
public static void main (String args [ )
try
int n=[Link] (args [0]) ;
int nl=[Link] (args [1]);
int n2=n + nl;
catch (ArithmeticException ex)
{
System. [Link] ("Arithinetic Exception block 1"):
}
catch (ArithmeticException ex)
{
[Link] ("Arithmetic Exception block 2"):
13.2 Which exception may be thrown if the given code is executed? 5 marks
class excep2
publiC static void main (String args ])
try
int n =
int nl = [Link] (args [0]) ;
[Link] (args [1]);
int n2 = n+nl;
[Link] .println ("Sum is " + n2) ;
catch (Arithmet icException ex)
Systeln. out. println ("Arithmetic M+ex .
getMe SSage 0); Exception :
Catch (NunberForma
LException ex)
Systefl . [Link] ("Format
getMesSage 0); Exception : +eX.
catch (Exception ex)
[Link]. println ("Exception :" + ex) ;
Managing Errors and Exceptions 249
codethrows an exceptionin case the desired input is not received. Debug the
The code. 2 marks
133class excep3
public static void main (String
args[])
if (args [0]=="Hello")
else
[Link] ("String is right") ;
throw new Exception ("Invaiid String");
134 Custom exception has been created in the code given below. Correct the code. 2 marks
class myexception extends Exception
myexception (String s)
super (s);
class excep4
public static void main (String args [])
if(args (0]=="Hello")
[Link] ("String is right");
else
try e
throw new myexcept ion ("Invalid String"):
}catch (myexception ex)
System. [Link] ([Link] ());
135 The program calculates sum of two numbers inputted as command-line arguments. When will it
give an exception? 2 marks
class excep
Public static void main (String []args)
Try { (args[0J);
int n = [Link]
[Link] (args[1D;
int nl =
int n2 = ntnl; n2) ;
is: "
System. [Link] ("Sum
Catch (NumberFormatException ex)
System. [Link] (ex) ;
What is Inheritance in Java? 2
What is super class and subclass? 2
Can a class extend more than one class? 2
Can we extend final class? 2
Can a final method be overridden? 2
Can we inherit private members of base class to its 2
subclass?
Can we access subclass members if we create an 2
object of superclass?
Can we override static method? 2
What is the difference between error and exception in 2
Java?
What is an exception? 2
What is an error? 2
Can we throw an exception manually? If yes, how? 2
What are the Exception Handling Keywords in Java? 2
What is Abstract class? 2
What is the use of super in java? 2
What is the difference between this() and super() in 2
Java?
Differentiate between static and non-static methods in 2
Java.
What is the difference between abstract classes and 2
interfaces?
Can we make the abstract methods static in Java? 2
Can you use this() and super() both in a constructor? 2
What is the difference between error and exception 2
How does Multiple inheritance implement in Java? 5
What are the advantages of using exception handling? 5
Write the syntax of Nested try catch block in Java. 5
Discuss different types of inheritance is possible in 5
JAVA.
Discuss final class with an example. 5
Write a JAVA program to demonstrate the use of static 5
member function.
Discuss static variable with proper example. 5
Discuss final variable with proper example 5
Show how a reference variable can refer an object and 5
how function can be called by that reference variable.
What are the differences between throw and throws? 5
Explain ‘this’ keywords with suitable example. 5
Explain different types of exception handling with 5
examples.
Write a program in java to create Box class with 10
parameterized constructor with an object argument to initialize
length, breadth and height also create a function volume which
returns the volume of the box and print it in main method.
Write down the difference between final, finally and 10
finalize in Java.
Explain what exceptions are in Java. Differentiate between 10
checked and unchecked exceptions with examples. Write a
simple Java program that uses a try-catch block to handle
ArithmeticException.
Write a Java program that takes two numbers as input and 10
performs division. Use multiple catch blocks to handle
ArithmeticException and InputMismatchException. Display
appropriate error messages.
Explain the purpose of the finally block in Java exception 10
handling. Write a Java program that reads a file, uses try-catch
to handle FileNotFoundException, and ensures file closing
using a finally block.
What is the difference between throw and throws in Java? Write 10
a Java program that creates a method to check if a number is
negative and throws an IllegalArgumentException if it is.
Write a Java program to create a custom exception called 10
InsufficientBalanceException. Create a BankAccount class with
a withdraw method that throws this exception if the balance is
insufficient.
Discuss best practices for exception handling in Java. Write a 10
program that simulates an online shopping cart, handling
exceptions such as invalid quantity, out-of-stock products, and
payment failures gracefully.