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
Comments
Post a Comment