Practical No.
23, 24 & 25
Program Code: Demonstrates exception handling using try, catch, and
finally block.
class Exception{
public static void main(String args[]){
int a,b,c;
try{
a = [Link](args[0]);
b = [Link](args[1]);
c = a/b;
[Link]("Division is: "+c);
catch (ArithmeticException e){
[Link]("Can't divided by zero");
finally {
a = [Link](args[0]);
b = [Link](args[1]);
c = a+b;
[Link]("Addition is: "+c);
}}}
Practical related question:
3. Can we throw exception manually? Illustrate with sample program
Yes, we can throw an exception manually in Java using throw keyword.
public class ExceptionExample {
public static void main(String[] args) {
try {
throw new Exception("Manually throwing an exception!");
} catch (Exception e) {
[Link]("Caught exception: " + [Link]());
}}}
Exercise:
1. The program calculates sum of two numbers inputted as
command-line arguments. When will it give an exception?
class excep{
public static void main(String args[])
try {
int n=[Link](args[0]);
int n1=[Link](args[1]);
int n2=n+n1;
[Link]("Sum is:"+n2);
catch(NumberFormatException ex){
[Link](ex);
} finally {
[Link]("You inputted a correct integer number");
}}}
2. Develop a program to accept a password from the user and throw
"Authentication Failure" exception if the password is incorrect.
3. Write the exception thrown by the following code block?
Integer[][] ints={(1, 2, 3), (null), (7,8,9)):
[Link]("value="+ints[1][1].intValue());
The following code block will throw a NullPointerException exception