+ 1
Describe exception handling
2 Antworten
+ 6
sometime in runtime program encounters to some sort of errors which can stop the normal flow of the program. For example assume your program needs to receive a number as input from the user but the user enters a string. At this time an exception occurs. To handle this situation the programmer should predict the possibility of occuring an exception and provide an alternative flow so the normal flow of the program does not stop and continue. For handling exceptions you should use try and catch and finally block.
+ 1
Exception Handling
I will try to put the concept as simple as possible.
Suppose, you write a java code which add two numbers.
And these two numbers are to be given by the user.
import java.util.Scanner;
class Demo
{
public static void main(String args[])
{
Scanner Sc = new Scanner (System.in);
int a, b;
System.out.println(Enter number 1 : );
a = Sc.nextInt();
System.out.println(Enter Number 2 : );
b = Sc.nextInt();
System.out.println("Sum is : " + (a + b));
}
}
Now here,
in the line where we taking 'a' input, the user is supposed to enter a integer value. But suppose where user mistakenly types a character, then what will happen?
Answer is our program will terminate showing the error details.
This is where Exception Handling comes into play. Here if we provide a code that handles the mistyped cases then we can prevent our program being terminated.
Happy CODING!