Practical_12
Practical_12
Conclusion
In this practical, we wrote programs to implement the try, catch, and finally blocks. We learned
how to handle exceptions in Java and ensure code execution in the finally block regardless of
exceptions.
} finally {
System.out.println("Finally block executed.");
}
}
}
2. Differentiate between error and exception in java.
Aspect Error Exception
A serious issue that occurs at A problem that occurs during
Definition runtime and is beyond user control. execution and can be handled by
the program.
Hardware failure, JVM issues, Invalid user input, division by
Causes
memory overflow, etc. zero, file not found, etc.
4. Develop a program to accept a password from the user and throw “Authentication Failure”
Exception if the password is incorrect.
import java.util.Scanner;
class PasswordCheck {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String correctPassword = "java123"; // Predefined password
try {
if (!inputPassword.equals(correctPassword)) {
throw new MyAuthenticationException("Authentication Failure");
}
System.out.println("Login Successful!");
} catch (MyAuthenticationException e) {
System.out.println(e.getMessage());
}
}
}
5. How exception is thrown by main method?
• In Java, the main method can throw an exception using the throws keyword.
• If an exception is not handled within main(), it propagates to the JVM, which prints an error
message and terminates the program.
Program: Throwing an Exception from main()
class MainExceptionDemo {
public static void main(String args[]) throws ArithmeticException {
int num = 10 / 0; // This will cause ArithmeticException
System.out.println("This line will not execute.");
}
}
• The main method is declared with throws ArithmeticException.
• The division by zero causes an ArithmeticException.
• Since it is not handled, the JVM terminates the program and prints an error message.