Exception Handling in Java

What is an Exception?

--An exception is a problem that arises during the execution of a program
--Its an event that disrupts the normal flow of the program

How exception occurs?

Following are some scenarios where an exception occurs.

1. A user has entered an invalid data.

2. A file that needs to be opened cannot be found.

3. A network connection has been lost in the middle of communications or the JVM has run out of memory.


Exception Classes
Exception Class Hierarchy


Types of java exceptions:

1. Checked Exception -  Checked exceptions are checked at compile-time so this is also called compile time exceptions. Example of checked exceptions are : ClassNotFoundException, IOException, SQLException and so on.They occur usually interacting with outside resources/network resources e.g. database problems, network connection errors, missing files etc.

2. UnChecked Exception - Unchecked exceptions are not checked at compile-time, but they are checked at runtime. Also Called Run time Exceptions. Example of unchecked exceptions are : ArithmeticException, ArrayStoreException, ClassCastException and so on.

3. Error - Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

How to handle exception?

Java exception handling is managed via five keywords:

try: this keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can't use try block alone.

catch:  this block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later.

finally: this block is used to execute the important code of the program. It is executed whether an exception is handled or not.

throw: this keyword is used to throw an exception.

throws: this keyword is used to declare exceptions. It doesn't throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature.

try catch syntax:

try{
//code that may throw an exception 
}catch(ExceptionClassName ref){
}


try finally block

try{
//code that may throw an exception 
}finally{
}

To get more details please watch below youtube video and Subscribe the channel.

https://www.youtube.com/watch?v=P-KR6Eq4CM0&feature=youtu.be

Part1:


Part2:


No comments:

Post a Comment