Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Workshop 07 in This Workshop, You'll Learn:: Exception Handling

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Exception handling

Workshop 07

In this workshop, you’ll learn:

 Exception Handling
 Multiple Handlers
 Code Finalization and Cleaning Up
 Custom Exception Classes

Create 2 exception classes named IllegalTriangleException and IllegalRightTriangleException as


customs exception classes.
Write a class named RightTriangle with three sides a, b, c is integer numbers.
In the constructor of class RightTriangle:
 If 3 integers is not 3 side of a triangle (The sum of any two sides is greater than the other side)
then throw IllegalTriangleException.
 If 3 integers is not 3 side of a right triangle (follow Pythagorean Theorem) then throw
IllegalRightTriangleException.

class RightTriangle{
int a, b, c;

//Constructor
public RightTriangle(int a, int b, int c)
throws IllegalTriangleException, IllegalRightTriangleException{
//implement it
}
}

1
Write a Java program to test the RightTriangle class. Three sides are accepted from keyboard and
check input validation

Sample output:
Enter side a: 6a
Wrong input! Try again!
Enter side a: 1
Enter side b: 2
Enter side c: 8
This is not a triangle!
Continue? (Y/N): Y

Enter side a: 6
Enter side b: 7
Enter side c: 8
This is not a right triangle!
Continue? (Y/N): Y

Enter side a: 3
Enter side b: 4
Enter side c: 5
This is a right triangle!
Continue? (Y/N): N

Main class should be like following:

public class Ex1_Ws2 {


public static void main(String[] args) {
int a, b, c;
Scanner nhap = new Scanner(System.in);
while (true) {
//enter integer a here with input validation
//enter integer b here with input validation

2
//enter integer c here with input validation

try {
//call constructor of RightTriangle class
RightTriangle rt = new RightTriangle(a, b, c);
System.out.println("This is a right triangle!");
} catch (IllegalTriangleException e1) {
System.out.println(“This is not a triangle!”);
} catch (IllegalRightTriangleException e2) {
System.out.println(“This is not a right triangle”);
}
//continue?
System.out.print("Continue?(Y/N):");
//Enter a character
char chon = nhap.next().charAt(0);
if(chon != 'Y')
break;
}
}
}

You might also like