Assignment - 8
1. Write a program to implement the concept of Exception Handling using predefined exception.
Code : import java.io.IOException;
import java.util.Scanner;
class Trump {
static void print(int arr[])throws IOException{
Scanner sc = new Scanner(System.in);
try {
System.out.println("Please enter 10 values : ");
for(int i = 0 ; i < 10; i++) {
arr[i] = sc.nextInt();
}
if(arr[0] >= 100) throw new IOException();
System.out.println("Please enter 2 index to divide element at that Index : ");
int idx1 = sc.nextInt();
int idx2 = sc.nextInt();
int ans = arr[idx1]/arr[idx2];
System.out.println("dividing element at index "+idx1+" by element at index "+idx2+"we get =
"+ans);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("CATCHES OUT OF BOUNDS EXCEPTION " +e);
}
catch(ArithmeticException e) {
System.out.println("CATCHES ARITHMETIC EXCEPTION " +e);
}
finally {
System.out.println("finally will always be executed ");
}
System.out.println("size of the array is = "+10);
}
}
public class print {
public static void main(String[] args) throws IOException{
Scanner sc = new Scanner(System.in);
int arr[] = new int[10];
Trump.print(arr);
}
}
output :
2. Write a program to implement the concept of Exception Handling by creating user defined
exceptions.
Code:
import java.io.IOException;
import java.util.Scanner;
class MyException extends Exception {
public String toString() {
return "Wrong password";
}
}
class Checker {
static void check(String userName, int password) throws IOException {
try {
if (userName.equals("admin") && password == 12345) {
System.out.println("You are now logged in as: " +userName);
} else {
throw new MyException();
}
if (password > 12345) {
throw new IOException();
}
} catch (MyException e) {
System.out.println("Please enter correct password: " + e);
} finally {
System.out.println("Finally block always printed");
}
System.out.println("Username = " + userName + ", Password = " +password);
}
}
public class ieh2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String userName;
int password;
System.out.println("Enter the Username: ");
userName = sc.next();
System.out.println("Enter the Password: ");
password = sc.nextInt();
try {
Checker.check(userName, password);
} catch (IOException e) {
System.out.println("IO Exception occurred: " + e);
}
}
}
Output: