#learnjava #learnjavabasics #javatutorial
Java Basics Day 3 | Java Tutorial
Java Tutorial for Beginners 2020
Learn Java programming from expert software engineers.
Day 3
Exception Handling
Demo
An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled.
An exception can occur for many different reasons. For Example:
A user has entered an invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications or the JVM has run out of memory.
A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception.
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}
The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception.
Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
}finally {
// The finally block always executes.
}
Throw keyword is used to explicitly throw an exception
throw new Exception(“Data not valid”)
Throws keyword is used in method signature to indicate that method throw an Exception
and Caller of that method either handle that exception or define throws with its methods signature.