Home | History | Annotate | Download | only in src
      1 /*
      2  * Copyright (C) 2012 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 import java.util.Random;
     18 
     19 /**
     20  * Tests long division by zero for both / and %.
     21  */
     22 public class ZeroTests {
     23     public void longDivTest() throws Exception {
     24       longTest("longDivTest", true);
     25     }
     26 
     27     public void longModTest() throws Exception {
     28       longTest("longModTest", false);
     29     }
     30 
     31     private static void longTest(String name, boolean divide) throws Exception {
     32       // Warm up JIT.
     33       for (int i = 0; i < 10000; ++i) {
     34         try {
     35           // We won't JIT code that hasn't completed successfully, so rhs can't be 0 here!
     36           if (divide) {
     37             longDiv(1, 1);
     38           } else {
     39             longMod(1, 1);
     40           }
     41         } catch (ArithmeticException expected) {
     42           throw new AssertionError(name + " threw during warmup");
     43         }
     44       }
     45 
     46       // Boom?
     47       int catchCount = 0;
     48       for (int i = 0; i < 10000; ++i) {
     49         try {
     50           if (divide) {
     51             longDiv(1, 0);
     52           } else {
     53             longMod(1, 0);
     54           }
     55           throw new AssertionError(name + " failed to throw: " + i);
     56         } catch (ArithmeticException expected) {
     57           ++catchCount;
     58         }
     59       }
     60       if (catchCount != 10000) throw new AssertionError(name + " failed: " + catchCount);
     61 
     62       System.out.println(name + " passes");
     63     }
     64 
     65     private static long longDiv(long lhs, long rhs) {
     66       return lhs / rhs;
     67     }
     68 
     69     private static long longMod(long lhs, long rhs) {
     70       return lhs % rhs;
     71     }
     72 }
     73