When we write a program, but it's having some error, It's can call exception. So that we want to learn about exception. Its very use full for identifying exception and fixed it.
Exceptions are can be divide into two sub topics. There are compile time exception and run time exception.
Compile Time Exception
This exception is thrown in compile time. Our codes have compile time exception, it's cannot be compilde until it's fixed. When the coding if we forgot brackets, type keyword with spelling mistakes, not used patten, .. etc, that code throw exception in compile time. That exception catches compiler and give an error.
Example:-
You can see the underline in red colour, those are indicate compile errors have in that line. This is a feature in Netbeans. When you try compile this code using command prompt, You can see error like this-
Run time Exception
This exception is cannot catch compiler. In this case we cannot identify this exception till the code is run. When the run time exception is thrown, But we cannot identify where this error have. In this case those type exceptions are more dangerous rather than complete time exceptions. Because compile time exceptions can identify easily.
Example:-
import java.util.Scanner;
public class ExceptionExample {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.print("Enter the value for x :-");
int x=s.nextInt();
System.out.print("Enter the value for y :-");
int y=s.nextInt();
int sum=x+y;
System.out.println("x+y ="+sum);
}
}
This is a simple example to run time exception.When the code is compiled, it's haven't any errors. When this code is run, it's required value for x and y. You must be give for it any two numbers. When you must give character for it, the code will throw exception at run time. Because we are not using the solution for catch this error in user input.
You can see we give "s" for second user input. In this case program throws run time exception InputMismatchException.
* The First error is we cannot assign "s" for integer variable.
* Second one is we cannot add integer and string.
******Next Lesson is about The Exception Handling.******
No comments:
Post a Comment