Exception study
After try block,
a catch clause appears.
What if your code does not handle an exception, what happen?
if your code does not handle an exception when it is thrown, the default exception handler deals with it. The default exception handler prints on error message and crashes the program.
try block
A try block is one or more statements that are executed and can potentially throw an exception. you can think of the code in the try block as being "protected " because the application will not halt if the try block throws an exception.
Exception Definition
An exception is an object that is generated as the result of an error or an unexpected event. To prevent exceptions from crashing your program, you must write code that detects and handle them.
getMessage()
Each exception object has a method named getMessage that can be used to retrieve the default error message for the exception. This is the same message that is displayed when the exception is not handled and the application halts.
Exception handler (Definition)
Exception handler is a section of code that gracefully responds to exceptions when they are thrown. The process of intercepting and responding to exceptions is called exception handling.
catch(FileNotFoundException e) This catch clause declares a reference variable named a as its parameter. What 'e' reference?
The e variablae can reference an object of the FileNotFoundException class. If the code in the try block throws an exception of the FileNotFoundException class, the e variable will reference the exception object and the code in the catch block will execute.
key word throws
The key word throws is written at the end of the method header, followed by a list of the types of exceptions that methods can throw.(if there is more than one type of exception, you separate them with commas)
Don't confuse the throw statement with the throws clause.
The throw statement causes an exception to be thrown. The throws clause informs the compiler that a method throws one or more exceptions.
finally clause
The try statement may have an optional finally clause, which must appear after all of the catch clauses. The finally block is one or more statements that are always executed after the try block has executed and after any blocks have executed if an exception was thrown. The statements in the finally block execute whether an exception occurs or not.
A catch clause begins with the key word catch followed by the code (ExceptionType parameterName).
This is a parameter variable declaration, where ExceptionTYpe is the name of an exception class and parameterName is a variable name.