The exeption handling in java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained
In here we learn
What is exception: From dictionary: Exception is a n abnormal condition.
In java, exception is an event that disrupt he flow of the program.It is an object which is thrown at runtime.
What is exception handling. Exception handling is a mechanism to handle runtimer errors such as ClassNotFound,IO,SQL,Remote etc.
The core advantage of excepion handling is to maintain the normal flow of the application.Exception normally disruts the normal flow of the application that is wh we use exception handling:
Let take the scenario:
1) Checked Exception: e.g: IOException,SQLException
The classes that extend throwable class except RuntimeException and Error are known as checked exceptions.Checked exceptiions are checked at compile time.
2} Unchecked exceptions: The classes that extend RuntimeExceptiona re known as unchecked exceptions e.g: ArithmeticException,NullPointerException,ArrayIndexOutOfBoundsException etc. Uncheked exceptions are not checked at compile time rather checked at run time.
3)Error: Error is irrecoverable e.g:OutOfMemoryError, VirtualMachineError, VirtualMachineError, AssertionError etc.
Java exception handliung keywords:
1.Try
2. catch
3. finally
4. throw
5. throws
1) Scenario where ArithemeticException occurs::
int a = 50/0; //Arithemetic Exception
2) Scenario where NullPointerException occurs
E.g:
String s=null; System.out.println(s.length()); //NullPointerException
3) Scenario where NumberFormatException occurs:
The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable that have characters, converting this variable into digit will occur NumberFormatException
String s="abc"; int i=Integer.parseInt(s); //NumberFormatException
4)Scenario where ArrayIndexOutOfBoundsException occurs
If you are inserting any value in the wrong index, It would result ArrayIndexOutOfBoundsException as shown below:
int a[]=new int[5]; a[10]=50; .//ArrayIndexOutOfBoundsException
throw vs throws:
Throw: You cannot throw multiple exceptions.
Throws: You can declare multiple exceptions e.g: public void method() throws IOException,SQLException etc.
Java throw example:
void m(){ throw new ArithmeticException("Sorry"); }
Java throws example:
void m() throws ArithmeticException{ //method code }
Java throw and throws example:
void m()throws ArithemticException { throw new ArithmeticException("sorry"); }
for further learning you can check out this link for reference: http://www.javatpoint.com/exception-handling-in-java