Site icon DataFlair

Java Program on throw Statement

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

Program 1

package beans;

import java.util.Scanner;

public class TestThrow 
{
    public static void main(String[] args) 
    {
             int a,b,c;
          try
          {    
              String s="DataFlair";
             Scanner scan=new Scanner(System.in);
             System.out.println("Enter first number");
             a=scan.nextInt();
             b=scan.nextInt();
             if(b==5)
              throw new ArithmeticException("Divide by five error");
//             if(b==0)
//              throw new ArithmeticException("Divide by zero error");
             c=a%b;
             System.out.println("Division is: " + c);
             
          }
          
          catch(Exception e)
          {
              System.out.println(e);
          }    
             
    }
    
}

Program 2

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package beans;

import java.util.Scanner;

/**
 *
 * @author admin
 */
public class TestThrow1 
{
    public static void main(String[] args) 
    {
       int a,b,c;
          try
          {    
              String s="DataFlair";
             Scanner scan=new Scanner(System.in);
             System.out.println("Enter first number");
             a=scan.nextInt();
             b=scan.nextInt();
             if(b==0)
              throw new ArithmeticException("Multiply by zero error");
             c=a*b;
             System.out.println("Multiplication is: " + c);
          }
          
          catch(Exception e)
          {
              System.out.println(e);
          }      
    }
    
}
Exit mobile version