Exception Handling in JAVA | How to use Try & Catch for Exception Handling

What is Exceptions in Java?

Exceptions are the errors which we can handle with the help of CODE. 
For instance - 

Error: Java out of memory: This error can not be handle with set of codes. We need to free up the space so that JAVA wont show us this error, 

However, 

Error: Index out of bound: This error can be handle by Using some code. This this is called an exception. The process of handling such exceptions is call Exception Handling.


Example for Index out of bound:

String Index our of bound Exception

Public Class A{

Static void B{
static String N = "Name" 

for (int i=0; i<=N.length; i++)

System our print{N.Charat(i)} 
}
}

HERE, after running this code in JAVA we will get index out of bound exception. 

Reason >>>  The java indexing starts from 0 and thus when we print the Character that is not present in the index order JAVA will throw StringIndexOutOfBound Exception 



How to handle Exceptions?

Exceptions are handle by using the Try, Catch & Finally blocks. 

  • Try

Try >> This holds the protected code where we are excepting an error . This defines the boundary for error code.

For Instance -  String Index Out Of Bound Exception


Public Class A{

Static void B{
static String N = "Name" 

{for (int i=0; i<=N.length; i++)
}
try {System.out.print(N.charAt(i));
catch (Exception X) {
System.out.print("IndexOutOfBOund");}
}

  • Catch

Catch >>> This holds the trigger code(a code which ) block holds the protected code where we are excepting an error . This defines the boundry for error code.

Public Class A{
Static void B{
static String N = "Name" 
{for (int i=0; i<=N.length; i++)
}
try {System.out.print(N.charAt(i));

catch (Exception X) {
System.out.print("IndexOutOfBOund");}
}

  • Finally

This block will execute always no matter if we get an exception or not

Examples of Exceptions in Java?

  • Checked Exceptions
This are also called as Compile time exceptions which are notified by JAVA while compiling the code. 

For Instance >>>> FileNotFoundException

  • Unchecked Exceptions  

This are also called as Run time exceptions which are notified by JAVA only after we run the code. 

For Instance>>>> NullPointerException


Difference between Throws and Throw keywords in Exception handling

  • Throw > This will trigger the exception
  • Throws >   This will postponed the exception and convert compile time exception into runtime exception



Comments