public class ArrayOutOfBounds {
    public static void main(String[] args) {
        int[] array = {1, 2, 3};
        
        try {
            int element = array[3]; // 数组越界,抛出ArrayIndexOutOfBoundsException异常
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("数组越界错误:" + e.getMessage());
        }
    }
}
package Test;
import java.io.*;
public class Test {
    /**
     * Write the bytes from input stream to output stream.
     * The input stream and output stream are not closed.
     * @param is
     * @param os
     * @throws IOException
     */
    public  boolean copy(InputStream is, OutputStream os) throws IOException {
        int count = 0;
        //缺少空指针判断
        byte[] buffer = new byte[1024];
        while ((count = is.read(buffer)) >= 0) {
            os.write(buffer, 0, count);
        }
        //未关闭I/O流
        return true;
    }
    /**
     * 
     * @param a
     * @param b
     * @param ending
     * @return copy the elements from a to b, and stop when meet element ending
     */
    public void copy(String[] a, String[] b, String ending)
    {
        int index;
        String temp = null;
        //空指针错误
        System.out.println(temp.length());
        //未使用变量
        int length=a.length;
        for(index=0; index&a.length; index++)
        {
            //多余的if语句
            if(true)
            {
                //对象比较 应使用equals
                if(temp==ending)
                {
                    break;
                }
                //缺少 数组下标越界检查
                b[index]=temp;
            }
        }
    }
    /**
     * 
     * @param file
     * @return file contents as string; null if file does not exist
     */
    public  void  readFile(File file) {
        InputStream is = null;
        OutputStream os = null;
            try {
                is = new BufferedInputStream(new FileInputStream(file));
                os = new ByteArrayOutputStream();
                //未使用方法返回值
                copy(is,os);
                is.close();
                os.close();
            } catch (IOException e) {
                //可能造成I/O流未关闭
                e.printStackTrace();
            } 
            finally
            {
                //空的try/catch/finally块
            }
    }
}
public class Singleton {
    private static Singleton singleton;
    private Singleton() {

    }
    public static Singleton getInstance() {
        if (singleton == null) {//1
            synchronized {//2
                if (singleton == null) {//3
                    singleton = new Singleton();//4             
                }
            }
        }
    }
}
$('#checkbox').prop('checked', true);
public DbConnection getDbConnection(String username, String password) {
try {
return new DbProvider().getConnect(username, password);
} catch (IOException e) {
throw new RuntimeException();
}
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class Main {
public static void main(String[] args) {
    File f = new File("C:\test.txt");
    FileReader r = new FileReader(f); //A
    BufferedReader br = new BufferedReader(r);
    br.readLine(); //B
    br.close(); //C
    }
}
public static void check(boolean condition, String errorMessage) {
    if (!condition) {
        throw new IllegalArgumentException(errorMessage);
    }
}
if 要判断的条件:
	条件成立时要做的事情
	...
else:
	条件不成立时要做的事情
12345
OCF_CHECK_LEVEL 属性允许在不同级别配置更深入的检查。 默认值为 0。将 OCF_CHECK_LEVEL 设置为 10 或 20 将导致资源监视器操作测试文件系统 I/O。

OCF_CHECK_LEVEL=10 实现对文件系统底层设备的读取测试。
OCF_CHECK_LEVEL=20 实现了文件系统的读写测试。 它写入状态文件,然后尝试从状态文件中读取。 

~~~
The OCF_CHECK_LEVEL attribute allows the configuration of more in-depth checks at different levels. The default value is 0. Setting OCF_CHECK_LEVEL to 10 or 20 will cause the resource monitor operation to test filesystem I/O.

OCF_CHECK_LEVEL=10 implements a read test of the device underlying the filesystem.
OCF_CHECK_LEVEL=20 implements both a read and a write test of the filesystem. It writes to a status file and then attempts to read from the status file.
~~~

关于这个问题的详细信息,请参考如下文档:

6.9. MULTIPLE MONITORING OPERATIONS
https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/high_availability_add-on_reference/s1-multiplemonitor-haar

How do I configure a filesystem resource to do a read or write check during a Monitor action in Red Hat Enterprise Linux with High Availability or Resilient Storage? - Red Hat Customer Portal
<build>
         <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-checkstyle-plugin</artifactId>
                <version>3.1.2</version>
                <dependencies>
                    <dependency>
                        <groupId>com.puppycrawl.tools</groupId>
                        <artifactId>checkstyle</artifactId>
                        <version>8.45</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <consoleOutput>true</consoleOutput>
                    <encoding>UTF-8</encoding>
                    <configLocation>style/checkstyle.xml</configLocation>
                    <failOnViolation>true</failOnViolation>
                    <violationSeverity>warning</violationSeverity>
                    <includeTestSourceDirectory>false</includeTestSourceDirectory>
                    <sourceDirectories>
                        <sourceDirectory>${project.build.sourceDirectory}</sourceDirectory>
                    </sourceDirectories>
                    <excludes>**\/generated-sources\/</excludes>
                </configuration>
                <executions>
                    <execution>
                        <phase>compile</phase>
                        <goals>
                            <goal>check</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
public class CheckUtils {
    
    public static void checkNotNull(Object obj, String message) {
        if (obj == null) {
            throw new IllegalArgumentException(message);
        }
    }
    
    public static void checkPositive(int num, String message) {
        if (num <= 0) {
            throw new IllegalArgumentException(message);
        }
    }
}
Javadoc Comments 
          JavadocPackage 
 检查每个java package中是否有java注释文件,默认是允许一个package-info.java,也可以通过allowLegacy属性配置允许package.html。 
          JavadocType 
 检查类和接口的javadoc。默认不检查author 和version tags。 
          JavadocMethod 
 检查方法和构造函数的javadoc。默认不检查未使用的异常抛出。 
          JavadocVariable 
 检查变量的javadoc。 
          JavadocStyle 
 检查javadoc的格式。比如:javadoc的第一行是否以句号结束,javadoc除了tags外是否有description,检查javadoc中的html格式。 
          WriteTag 
 输出javadoc中的tag。 
 Naming Conventions 
         AbstractClassName 
 检查抽象类名。 
          ClassTypeParameterName 
 检查类的Parameter名。 
          ConstantName 
 检查常量名。 
          LocalFinalVariableName 
 检查局部的final类型变量名,包括catch的参数。 
          LocalVarableName 
 检查局部的非final类型的变量名,包括catch的参数。 
          MemberName 
 检查非静态变量。 
          MethodName 
 检查方法名。 
          MethodTypeParameterName 
 检查方法的参数名。 
          PackageName 
 检查包名。 
          ParameterName 
 检查参数名。 
          StaticVariableName 
 检查静态的,非final类型的变量名。 
          TypeName 
 检查类名和接口名。 
 Imports 
          AvoidStarImport 
 检查是否有使用*进行import。 
          AvoidStaticImport 
 检查是否有静态import。比如是否导入了java.lang包中的内容。 
          IllegalImport 
 检查是否import了违法的包。默认拒绝import所有sun.*包。 
          RedundanImport 
 检查是否有重复的import。 
          UnusedImports 
 检查是否有未使用的import。 
          ImportOrder 
 检查import的分组和顺序。 
          ImportControl 
 控制可import的包。在一个较大的project可限制使用过多的第三方包,通过一个依照http://www.puppycrawl.com/dtds/import_control_1_0.dtd的xml文件来指定。 
 Size Violations 
          ExecutableStatementCount 
 限制可执行代码片段的长度。默认为30。 
          FileLength 
 检查java文件的长度。默认为2000。 
          LineLength 
 检查代码行的长度。默认为80。 
          MethodLength 
 检查方法和构造函数的长度。默认为150。 
          AnonInnerLength 
 检查匿名内部类的长度。默认为20。 
          ParameterNumber 
 检查方法和构造函数的参数个数。默认为7。 
 Whitespace 
         GenericWhitespace 
 检查<和>周围的空白。 
          EmptyForInitializerPad 
 检查空的初始化位置的空白。比如for循环中的初始化。 
          EmptyForIteratorPad 
 检查空的迭代位置的空白。 
          MethodParamPad 
 检查方法签名之前的空白。 
          NoWhitespaceAfter 
 检查分隔符后的空白。 
          NoWhitespaceBefore 
 检查分隔符前的空白。 
          OperatorWrap 
 检查操作符的空白规则。 
          ParenPad 
 检查圆括号的空白规则。 
          TypecaseParenPad 
 检查强制转型的圆括号的空白规则。 
          TabCharacter 
 检查是否有Tab字符(’"t’)。 
          WhitespaceAfter 
 检查分隔符是否在空白之后。 
          WhitespaceAround 
 检查分隔符周围是否有空白。 
 ModifierOrder 
          ModifierOrder 
 检查修饰符的顺序是否遵照java语言规范。 
          RedundantModifier 
 检查接口和annotation中是否有重复的修饰符。 
 Block Checks 
          EmptyBlock 
 检查空的代码块。 
          LeftCurly 
 检查’{’和左边的代码块是否在同一行。 
          NeedBraces 
 检查是否需要大括号。主要是在if,else时的情况。 
          RightCurly 
 检查’}’。 
          AvoidNestedBlocks 
 检查不需要的嵌套’{}’。 
 Coding 
          ArrayTrailingComma 
 检查数组初始化是否以逗号结束。 
          AvoidInlineConditionals 
 检查inline的条件操作。 
          CovariantEquals 
 检查类是否覆盖了equals(java.lang.Object)。 
          DoubleCheckedLocking 
 检查DCL的问题。 
          EmptyStatement 
 检查空的代码段。 
          EqualsAvoidNull 
 检查一个可能为null的字符串是否在equals()比较的左边。 
          EqualsHashCode 
 检查类是否覆盖了equals()和hashCode()。 
          FinalLocalVariable 
 检查未改变过的局部变量是否声明为final。 
          HiddenField 
 检查局部变量或参数是否隐藏了类中的变量。 
          IllegalInstantiation 
 检查是否使用工厂方法实例化。 
          IllegalToken 
 检查非法的分隔符。 
          IllegalTokenText 
 检查非法的分隔符的下个字符。 
          InnerAssignment 
 检查子表达式中是否有赋值操作。 
          MagicNumber 
 检查是否有“magic numbers”。 
          MissingSwitchDefault 
 检查switch语句是否有default的clause。 
          ModifiedControlVariable 
 检查循环控制的变量是否在代码块中被修改。 
          RedundantThrows 
 检查是否有被重复抛出的异常。 
          SimplifyBooleanExpression 
 检查是否有过度复杂的布尔表达式。 
          SimplifyBooleanReturn 
 检查是否有过于复杂的布尔返回代码段。 
          StringLiteralEquality 
 检查字符串是否有用= =或!=进行操作。 
          NestedIfDepth 
 检查嵌套的层次深度。 
          NestedTryDepth 
 检查try的层次深度。 
          NoClone 
 检查是否覆盖了clone()。 
          NoFinalizer 
 检查是否有定义finalize()。 
          SuperClone 
 检查覆盖的clone()是否有调用super.clone()。 
          SuperFinalize 
 检查覆盖的finalize()是否有调用super.finalize()。 
          IllegalCatch 
 检查是否catch了不能接受的错误。 
          IllegalThrows 
 检查是否抛出了未声明的异常。 
          PackageDeclaration 
 检查类中是否有声明package。 
          JUnitTestCase 
 确保setUp(), tearDown()方法签名的正确性。 
          ReturnCount 
 限制return代码段的数量。 
          IllegalType 
 检查未使用过的类。 
          DeclarationOrder 
 检查类和接口中的声明顺序。 
          ParameterAssignment 
 检查不允许的参数赋值。 
          ExplicitInitialization 
 检查类和对象成员是否初始化为默认值。 
          DefaultComesLast 
 检查default的clause是否在switch代码段的最后。 
          MissingCtor 
 检查类依赖。 
          FallThrough 
 检查switch代码的case中是否缺少break,return,throw和continue。 
          MultipleStringLiterals 
 检查一个文件中是否有多次出现的字符串。 
          MultipleVariableDeclarations 
 检查代码段和代码行中是否有多次变量声明。 
          RequireThis 
 检查代码中是否有“this.”。 
          UnnecessaryParentheses 
 检查是否有使用不需要的圆括号。 
 Class Design 
          VisibilityModifier 
 检查类成员的可见度。 
          FinalClass 
 检查只有private构造函数的类是否声明为final。 
          InterfaceIsType 
 检查接口是否仅定义类型。 
          HideUtilityClassConstructor 
 检查工具类是否有putblic的构造器。 
          DesignForExension 
 检查类是否为扩展设计。 
          MutableException 
 确保异常是不可变的。 
          ThrowsCount 
 限制抛出异常的数量。 
 Duplicate Code 
          StrictDuplicateCode 
 严格检查重复代码。 
 Miscellaneous 
          GenericIllegalRegexp 
 正则表达式的模式检查。 
          NewlineAtEndOfFile 
 检查文件是否以一个空行结束。 
          TodoComment 
 检查TODO:注释。 
          Translation 
 检查property文件中是否有相同的key。 
          UncommentedMain 
 检查是否有未注释的main方法。 
          UpperEll 
 检查long型约束是否有大写的“L”。 
          ArrayTypeStyle 
 检查数组类型定义的样式。 
          FinalParameters 
 检查方法名、构造函数、catch块的参数是否是final的。 
          Indentation 
 检查代码中正确的缩进。 
          TrailingComment 
 确保是否要代码行注释。 
          RequiredRegexp
import java.io.FileNotFoundException;

import com.apesource.demo.exception.CountTooLargeException;

public class Test {
	public static void main(String[] args)  {
		// 如果方法声明中包含Checked 异常类型
		// 则该方法的调用,必须使用try...catch处理
		try {
			dosth();
			donothing();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (CountTooLargeException e) {
			e.printStackTrace();
		} 
	}
	
	public static void dosth() throws FileNotFoundException{
		int a = 23,b=33;
	
		if(a > b) {
			// 如果抛出的异常对象类型是一个No Checked异常,则可以使用throws声明异常类型
			// throw new NullPointerException();
			
			// 如果抛出的异常对象类型是一个Checked异常,则必须使用throws声明异常类型
			throw new FileNotFoundException();
		}
		
		System.out.println();
	}
开发工具与关键技术:MyEclipse 10、Java
作者:潘玉莹
撰写时间:2019-06-14
public class CheckExample {
    public static void main(String[] args) {
        int x = 10;
        assert x == 10 : "x不等于10";
    }
}
1
private static Singleton _instance;
2

3
public static Singleton getInstance() {
4
        if (_instance == null) {
5
            _instance = new Singleton();
6
        }
7
        return _instance;
8
}
<configuration>
    <module name="Checker">
        <module name="TreeWalker">
            <module name="Indentation">
                <property name="basicOffset" value="4" />
                <property name="braceAdjustment" value="0" />
                <property name="caseIndent" value="4" />
                <!-- ... other configuration options -->
            </module>
            <!-- ... other modules -->
        </module>
    </module>
</configuration>
1)getMessage():返回该异常的详细描述字符串;
    2)printStackTrace():将该异常的跟踪栈信息输出到标准错误输出。
    3)printStackTrace(PrintStream s):将该异常的跟踪栈信息输出到指定输出流;
    4)getStackTrace():返回该异常的跟踪栈信息。
设置表中某字段的NK约束:create  table  table_name(
										属性名  数据类型  NOT  NULL,
												...................
										);
  • 1
  • 2
  • 3
  • 4
  • 5