› Understand the importance of Defensive Programming;
› Use the Exception Class to improve the robustness of a Java
› Catch system generated Exceptions using the try – catch structure;
› Display system-generated Exception messages;
› Display programmer generated Exception messages;
› Use the finally block;
› Design a testing strategy and associated test data.
What will happen during compilation?
What will happen during runtime?
› An exception is an exceptional event or error that occur during
program execution and interrupt the flow of the program.
› Defensive programming is the tactic of writing code to reduce
future, unanticipated problems i.e. exception.
› It can be done by reducing code complexity, validating all user
input and data.
› This display of red lines of error messages is called a stack
trace. The stack trace lists the classes and methods that the
exception passed through before the program was aborted.
Types of Exception
› The exceptions are broadly classified into two categories, namely,
1. checked exceptions and
2. unchecked exceptions.
› Exceptions that must be handled explicitly by the code are called
› e.g. SQLException, IOException
› In java, java.lang.Exception is a checked exception and all its
subclasses will also be checked.
› For checked exceptions, you either have to put a try/catch block
around the code or add a "throws" clause to the method, to
indicate that the method might throw this type of exception.
› Exceptions that do not need to be handled explicitly are called an
› e.g. ArithmeticException, NumberFormatException.
› In java java.lang.RuntimeException is an unchecked exception and
so are all its subclasses.
The throws clause
› The throws clause is used when we know that a method may cause
exceptions, but the method does not handle those exceptions.
› In such a case, a user has to throw those exceptions to the caller
of the method by using the throws clause.
› A throws clause is used when a method is declared.
The throw clause
› Till now, we have learned about catching exceptions thrown by JRE.
› In this section, we will learn to throw exceptions explicitly i.e.
› We can throw an object of any exception type in Java by using the
new operator with throw clause.