0% found this document useful (0 votes)
2 views

Exceptions

The document provides a tutorial on exceptions in Java, explaining what exceptions are, reasons for their occurrence, and categorizing them. It includes a code example demonstrating an ArithmeticException caused by division by zero, and outlines a task to create a program that validates user input for age and name, throwing a custom exception for invalid age inputs. The tutorial emphasizes exception handling and user input validation in Java programming.

Uploaded by

欧文苔藓
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Exceptions

The document provides a tutorial on exceptions in Java, explaining what exceptions are, reasons for their occurrence, and categorizing them. It includes a code example demonstrating an ArithmeticException caused by division by zero, and outlines a task to create a program that validates user input for age and name, throwing a custom exception for invalid age inputs. The tutorial emphasizes exception handling and user input validation in Java programming.

Uploaded by

欧文苔藓
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

JAVA

Tutorial- Exceptions
1. What Is an Exception in Java?
2. Why Exception Occurs? Give 4 reasons
3. Give the 2 Java Exception Categories
4. Copy the following code and run it then explain in detail on what happens. Where does it get
this message java.lang.ArithmeticException: / by zero

1. public class TryCatchExample4 {

2.

3. public static void main(String[] args) {

4. try

5. {

6. int data=50/0; //may throw exception

7. }

8. // handling the exception by using Exception class

9. catch(Exception e)

10. {

11. System.out.println(e);

12. }

13. System.out.println("rest of the code");

14. }

15.

16. }

5. Write a Java program that prompts the user to enter their name and age, validates the input
and prints a greeting message to the console. If the user enters an invalid age, the program
shouw throw a custom exception called “InvalidInputException” the program should be
implemented as follows.
a. Create a custom exception class called “InvalidInputException” that printsout the
message “Invalid age: Age should be a positive integer less than or equal to 120” if
the age is a negative number or greater than 120
b. Create another class “GreetingValidator” to get the user user inputs through the
main method. The program should prompt the user to enter their name and age.
c. The program should validate the age by checking that it is a positive integer less than
or equal to 120. If the age is invalid, the program should throw an
InvalidInputException.
d. If both the age is valid, the program should print a greeting message to the console
that includes the user’s name and age.

You might also like