Throw

To "Throw" something means to toss or cast it in the air, to discard or abandon something, or to give up on a problem or situation. In a more figurative sense, "throw" can mean to make or force someone to do something, or to attack or insult someone. The word can also have different meanings depending on the context in which it is used


  class MyException extends Exception
  {
      private int detail; 
      
      MyException(int a)
      {
          detail = a;
      }

      public String toString()
      {
          return "MyException [" + detail + " ]";
      }
  }

  class Throw1
  {
      static void compute(int a) throws MyException
      {
          System.out.println("Called compute(" + a + ")");
          
          if (a > 10)
              throw new MyException(a);

          System.out.println("Normal exit");
      }

      public static void main(String args[])
      {
          try
          {
              compute(1);
              compute(20);
          }
          catch(MyException e)
          {
              System.out.println("Caught " + e);
          }
      }
  }

Output:


  import java.util.Scanner;

  class MyException extends Exception
  {
      private int detail; 
      
      MyException(int a)
      {
          detail = a;
      }

      public String toString()
      {
          return "MyException[" + detail + "]";
      }
  }

  class Throw2
  {
      static void compute(int p, int c, int m, int b) 
      throws MyException
      {
          if (p > 100) 
              throw new MyException(p);

          if (c > 100)
              throw new MyException(c);

          if (m > 100)
              throw new MyException(m);

          if (b > 100)
              throw new MyException(b);

          System.out.println("Normal exit");
      }

      public static void main(String ar[])
      {
          try
          {
              Scanner s = new Scanner(System.in);
              
              System.out.println("Enter the Marks for Physics : ");
              int p = s.nextInt();

              System.out.println("Enter the Marks for Chemistry: ");
              int c = s.nextInt();

              System.out.println("Enter the Marks for Maths: ");
              int m = s.nextInt();

              System.out.println("Enter the Marks for Biology: ");
              int b = s.nextInt();

              int t = p + c + m + b;

              compute(p, c, m, b);

              System.out.println("Total = " + t);
          }
          catch(MyException e)
          {
              System.out.println("Marks can't be more than 100: " + e);
          }
      }
  }

Output: