1public static void foo() throws IOException {
2 // some code here, when something goes wrong, you might do:
3 throw new IOException("error message");
4}
5
6public static void main(String[] args) {
7 try {
8 foo();
9 } catch (IOException e) {
10 System.out.println(e.getMessage());
11 }
12}
1public void doChangePin(int oldPin, int pin) throws Exception { //need to add throws followed by exception name
2 if (oldPin == pinCode) {
3 pinCode = pin;
4 } else {
5 throw new Exception("some message"); //throwing the exception by creating its new object
6 }
7 }
1throw new java.lang.Error("this is very bad");
2throw new java.lang.RuntimeException("this is not quite as bad");
1public static void main(String[] args) {
2 Scanner kb = new Scanner(System.in);
3 System.out.println("Enter a number");
4 try {
5 double nb1 = kb.nextDouble();
6 if(nb1<0)
7 throw new ArithmeticException();
8 else System.out.println( "result : " + Math.sqrt(nb1) );
9 } catch (ArithmeticException e) {
10 System.out.println("You tried an impossible sqrt");
11 }
12}
1/* In this program we are checking the Student age
2 * if the student age<12 and weight <40 then our program
3 * should return that the student is not eligible for registration.
4 */
5public class ThrowExample {
6 static void checkEligibilty(int stuage, int stuweight){
7 if(stuage<12 && stuweight<40) {
8 throw new ArithmeticException("Student is not eligible for registration");
9 }
10 else {
11 System.out.println("Student Entry is Valid!!");
12 }
13 }
14
15 public static void main(String args[]){
16 System.out.println("Welcome to the Registration process!!");
17 checkEligibilty(10, 39);
18 System.out.println("Have a nice day..");
19 }
20}