目的
Javaソース内で例外が発生した場合は「BUILD FAILED」が表示されるようにする方法を記す
サンプル
SampleAnt.java(呼び出すJavaプログラム)
* 引数 args が、nullの場合、例外を発生させる
package com.sample.ant;
public class SampleAnt {
public static void main(String[] args) throws Exception {
if (args == null) {
throw new Exception("args == null");
}
for (String arg : args) {
System.out.println("Hello world, " + arg);
}
}
}
* Javaプログラムを呼び出す(引数なし)だけの build.xml
<project basedir="." default="sample.java.exception" name="SampleJavaCodes">
<target name="init" description="初期化">
<property name="class.path" value="./class" />
<delete dir="${class.path}"/>
<mkdir dir="${class.path}"/>
</target>
<target name="compile" depends="init" description="Javaコンパイル">
<javac srcdir="./src" destdir="./class" />
</target>
<target name="sample.java.exception" depends="compile" description="Java実行">
<echo message="execute Java" />
<java classname="com.sample.ant.SampleAnt" classpath="${class.path}">
</java>
</target>
</project>
ビルド結果(対応前)
* 「sample.java.exception」になっているにもかかわらず、「BUILD SUCCESSFUL」が表示される
Buildfile: C:\workspace\SampleJavaCodes\build.xml
init:
・・・略・・・
[javac] Compiling 1 source file to C:\workspace\SampleJavaCodes\class
sample.java.exception:
[echo] execute Java
BUILD SUCCESSFUL
Total time: 1 second
■対応方法
* javaタグに「erroeonfail="true"」を付加する
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project basedir="." default="sample.java.exception" name="SampleJavaCodes">
<target name="init" description="初期化">
<property name="class.path" value="./class" />
<delete dir="${class.path}"/>
<mkdir dir="${class.path}"/>
</target>
<target name="compile" depends="init" description="Javaコンパイル">
<javac srcdir="./src" destdir="./class" />
</target>
<target name="sample.java.exception" depends="compile" description="Java実行">
<echo message="execute Java" />
<java classname="com.sample.ant.SampleAnt" classpath="${class.path}" erroeonfail="true">
</java>
</target>
</project>
ビルド結果(対応後)
* 「BUILD FAILED」が表示される
Buildfile: C:\workspace\SampleJavaCodes\build.xml
init:
[delete] Deleting directory C:\workspace\SampleJavaCodes\class
[mkdir] Created dir: C:\workspace\SampleJavaCodes\class
compile:
[javac] C:\workspace\SampleJavaCodes\build.xml:9: warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds
[javac] Compiling 1 source file to C:\workspace\SampleJavaCodes\class
sample.java.exception:
[echo] execute Java
BUILD FAILED
C:\workspace\SampleJavaCodes\build.xml:13: java doesn't support the "erroeonfail" attribute
Total time: 1 second