0% found this document useful (0 votes)
10 views4 pages

Java Exception Handling Examples

The document contains 6 Java code examples demonstrating exception handling: 1. A program that reads an integer, checks if it's negative, and throws an exception with a message if so. 2. A program that reads an array of integers, checks if any are out of range [0-100], and throws an exception with a message if so. 3. A program that reads an email, checks if it's valid format, and throws an exception with a message if invalid. 4. A program that reads a file name, checks if the file exists, and throws an exception with a message if not found. 5. A program that divides two numbers, checks if the divisor is

Uploaded by

Ch Subhash
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views4 pages

Java Exception Handling Examples

The document contains 6 Java code examples demonstrating exception handling: 1. A program that reads an integer, checks if it's negative, and throws an exception with a message if so. 2. A program that reads an array of integers, checks if any are out of range [0-100], and throws an exception with a message if so. 3. A program that reads an email, checks if it's valid format, and throws an exception with a message if invalid. 4. A program that reads a file name, checks if the file exists, and throws an exception with a message if not found. 5. A program that divides two numbers, checks if the divisor is

Uploaded by

Ch Subhash
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1. Write a Java program that reads an integer from the user and checks if it is negative.

If
it is negative, throw an exception with a message "The number cannot be negative".
Catch the exception and display the message.”

1)
import [Link];

public class ExceptionHandling {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter an integer: ");
int num = [Link]();
try {
if (num < 0) {
throw new Exception("The number cannot be negative");
}
} catch (Exception e) {
[Link]([Link]());
}
}
}

2. Write a Java program that reads an array of integers from the user and checks if any
of the numbers are out of the range [0, 100]. If any of the numbers are out of range,
throw an exception with a message "The number must be between 0 and 100". Catch
the exception and display the message."

java
import [Link];

class RangeException extends Exception {


public RangeException(String message) {
super(message);
}
}

class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the number of integers: ");
int n = [Link]();
int[] arr = new int[n];
[Link]("Enter the integers:");
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}
try {
for (int i = 0; i < n; i++) {
if (arr[i] < 0 || arr[i] > 100) {
throw new RangeException("The number must be between 0 and 100");
}
}
[Link]("All numbers are within the range [0, 100]");
} catch (RangeException e) {
[Link]([Link]());
}
}
}
3. Write a Java program that reads a string from the user and checks if it is a valid email
address. If it is not a valid email address, throw an exception with a message "The
email address is not valid". Catch the exception and display the message."

java
import [Link];

class InvalidEmailException extends Exception {


public InvalidEmailException(String message) {
super(message);
}
}

class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter an email address: ");
String email = [Link]();
try {
if (![Link]("@") || ![Link](".")) {
throw new InvalidEmailException("The email address is not valid");
}
[Link]("The email address is valid");
} catch (InvalidEmailException e) {
[Link]([Link]());
}
}
}

4. Write a Java program that reads a file name from the user and checks if the file exists.
If the file does not exist, throw an exception with a message "The file does not exist".
Catch the exception and display the message.

java
import [Link].*;
import [Link];

public class FileCheck {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the file name: ");
String fileName = [Link]();

try {
File file = new File(fileName);
if (![Link]()) {
throw new FileNotFoundException("The file does not exist");
}
[Link]("The file exists");
} catch (FileNotFoundException e) {
[Link]([Link]());
}
}
}

5. Write a Java program that divides two numbers and checks if the divisor is zero. If the
divisor is zero, throw an exception with a message "The divisor cannot be zero".
Catch the exception and display the message.
java
import [Link];

public class DivideByZero {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the numerator: ");
int numerator = [Link]();
[Link]("Enter the denominator: ");
int denominator = [Link]();

try {
if (denominator == 0) {
throw new ArithmeticException("The divisor cannot be zero");
}
int result = numerator / denominator;
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]([Link]());
}
}
}

6. Write a Java program that creates an interface Shape with methods calculateArea and
calculatePerimeter. Implement the interface in two classes Rectangle and Circle.

java
interface Shape {
double calculateArea();
double calculatePerimeter();
}

class Rectangle implements Shape {


private double width;
private double height;

public Rectangle(double width, double height) {


[Link] = width;
[Link] = height;
}

@Override
public double calculateArea() {
return width * height;
}

@Override
public double calculatePerimeter() {
return 2 * (width + height);
}
}

class Circle implements Shape {


private double radius;

public Circle(double radius) {


[Link] = radius;
}

@Override
public double calculateArea() {
return [Link] * radius * radius;
}

@Override
public double calculatePerimeter() {
return 2 * [Link] * radius;
}
}

Common questions

Powered by AI

Implementing custom exception classes in Java can significantly enhance user experience by providing more intuitive and informative error messages tailored to specific application contexts, such as in educational or commercial software. By clearly defining and handling domain-specific exceptions, users receive comprehensive guidance on rectifying input or operational errors, which aids in understanding how to use the software effectively. This leads to better user engagement and satisfaction as the software behaves predictably and educatively when issues arise, instilling confidence and reducing frustration, thus fostering user loyalty and trust .

Proper exception handling enhances system reliability by allowing Java programs to manage unexpected situations without crashing, thereby maintaining uninterrupted service. Although exception handling introduces a slight overhead due to the additional control flow logic, the impact on performance is often outweighed by the benefits. By preventing unexpected termination and allowing programs to recover or fail gracefully, exception handling increases system robustness and reliability, which is crucial in mission-critical applications where downtime is costly. It also aids in pinpointing issues for efficient debugging and maintenance .

Validating email formats in Java applications is crucial to ensure data integrity and prevent erroneous data entries from disrupting application workflows. Exception handling is used to check that email inputs contain essential parts like '@' and '.', throwing exceptions for invalid formats. Without such validation, applications might accept malformed data leading to operational failures, security vulnerabilities, or rendering issues in systems depending on accurate email formats for notifications or user identification. Validation is a safeguard against common user errors, ensuring only correct and useful data is processed .

Checking for file existence before accessing a file is crucial because attempting to access a non-existent file can lead to runtime errors, causing the program to crash. By checking the file's existence and using exception handling, the program can preemptively manage potential issues, providing informative feedback instead of allowing an unhandled exception to crash the program. This improves the program’s reliability and user interface by ensuring that users are informed with a 'The file does not exist' message when an error occurs, allowing for corrective action without termination of the program .

Using custom exception classes, like the 'RangeException' in Java, provides specificity and clarity in expressing what exceptional condition has occurred, making the code more readable and maintainable. It allows programmers to handle specific cases more precisely. However, it can lead to excessive custom exception definitions, increasing complexity if not used judiciously. Compared to built-in exceptions, custom exceptions require more initial effort to define but can enhance clarity and specificity in error handling scenarios where built-in exceptions might not adequately describe the situation .

The try-catch block in Java offers several advantages over traditional error checking methods. It provides a centralized approach to handle errors, separating the error-handling logic from the main program flow. This leads to cleaner and more maintainable code by encapsulating what might go wrong within blocks that explicitly handle different exceptions. Furthermore, this allows for broader exception handling where multiple error types can be caught and managed within a single framework, improving code robustness and readability. It encourages developers to anticipate errors comprehensively and handle them in an organized manner, which contrasts with manual checks scattered across code that can be inconsistent and difficult to manage .

Specific exception messages significantly aid in debugging by clearly indicating the type of error encountered and the context in which it occurred, allowing developers to identify and fix bugs more efficiently. In user interaction scenarios, these messages enhance the user experience by providing explicit feedback, guiding users towards resolving issues on their own, such as reminding them of input constraints ('The divisor cannot be zero'). This practice also contributes to the maintainability of code by improving readability and understanding of exception handling processes without requiring developers to delve deep into the underlying code structure .

Java program design should incorporate robust error handling, especially when dealing with arithmetic operations like division, which can result in division by zero. Defining an ArithmeticException allows for graceful error management when the denominator is zero, allowing the program to provide a meaningful response ('The divisor cannot be zero') instead of terminating unexpectedly. This defensive design strategy ensures the program continues to function correctly even when encountering numerical errors, promoting stability and enhancing user interaction by handling potential pitfalls in runtime calculations .

Implementing interfaces in Java fosters key object-oriented programming (OOP) principles such as abstraction, encapsulation, and polymorphism. The Shape interface defines a contract (methods 'calculateArea' and 'calculatePerimeter') that any implementing class (e.g., Rectangle, Circle) must fulfill, promoting code abstraction. It increases flexibility and reusability as different shapes have their specific implementations, but all conform to the same interface. This setup enables polymorphism, allowing the same interface type to reference objects of different implementing classes, thus facilitating easier code management and scalability .

Exception handling in Java enhances the robustness of programs by allowing them to deal gracefully with errors or exceptional situations without crashing. In the provided Java program, when a user inputs a negative integer, an exception is thrown with the message 'The number cannot be negative'. By catching this exception, the program can display a meaningful message to the user instead of terminating unexpectedly. This not only improves user experience but also maintains the stability of the program, making it more robust against invalid user inputs .

You might also like