Java Learning Notes_140713 (Exception Handling)


Exception Handling (continued)

You can also use the Exception class, but basically you do individual exception handling (it doesn't make much sense if you don't know what kind of exception it is).

}catch(NumberFormatException e){

Exception Class Methods

  • public exception class name(): no-argument constructor
  • public exception class name (String message): A constructor with a message string as an argument
  • public void printStackTrace(): Display stack trace
  • public String getMessage() : Get the message string

}catch(Exception e){

The exception is not food

Never do anything while catching exceptions.

Throwing Exceptions
public class ThrowError {
    public static void main(String[] args) {
        int result = divOneTwo(args);
        System.out.println("result : " + result);
    static int divOneTwo(String[] args){
        if(args.length < 2){
            IllegalArgumentException e = new IllegalArgumentException("引数は2つ指定してください。");
            throw e;
            throw new IllegalArgumentException("引数は2つ指定してください。");
        return Integer.parseInt(args[0]) / Integer.parseInt(args[1]);

Checked and unchecked exceptions

  • Checked Exceptions: Exceptions That Should Always Be Checked / java.lang.InterruptedException,
  • Unchecked Exceptions: Exceptions That Can Occur Anywhere / java.lang.NullPointerException java.lang.IndexOutOfBoundsException

The checked exception must always describe the handling when an exception is thrown.


  1. Exception try{...} catch{...} Catch in
  2. Make a throw declaration (leave the processing to the caller of the method)

Do any of the processing.
public class ThreadSample {
    public static void main(String[] args) {

    static void sleep2s(){

        }catch(InterruptedException e){
public class ThreadSample2 {
    public static void main(String[] args) throws InterruptedException {

    static void sleep2s() throws InterruptedException{

In Eclipse, if you do not write exception handling, an error is displayed, and when you click on the corresponding part, you can choose whether to declare try{}catch{} or throw. Useful.


For large applications, errors and stack traces are output to a log file. There are many cases where java.util.logging or a library called Log4J are used.

I omitted the problem because I did it when reading.

Console input and exit

Use the scanner class. As I was doing earlier, summarize the main constructors and methods.

name explanation
Scanner (InputStream source) Constructor (InputStream as argument)
Scanner (File source) Constructor (File is the argument)
Scanner (String source) Constructor (String is an argument)
public Scanner useDelimiter(String pattern) Specify delimiters, arguments can describe regular expression patterns
public String next() Return the next token
public boolean hasNext() Returns the existence of the next token as boolean
public String nextLine() Reads the string up to the next line
public boolean hasNextLine() Return the next row as boolean
public int nextInt() Return the following token as int type
public boolean hasNextInt() Returns the boolean value if the following token exists and is of type int
public double nextDouble() Return the following token as double type
public boolean hasNextDouble() Returns a boolean value if the following token exists and is of type double
import java.util.Scanner;

public class ScannerSample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(;
            double d = sc.nextDouble();
            System.out.println("入力された数値 : " + d);

        else if(sc.hasNextInt()){
            int i = sc.nextInt();
            System.out.println("入力された整数 : " + i);

        else if(sc.hasNext()){
            String str =;
            System.out.println("入力された文字 : " + str);



In this case, it will be output as double type or as a string.
import java.util.Scanner;

public class MultipleInputSample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(;
            String s =;
            System.out.println("入力された文字 : " + s);

The scanner class was introduced in Java5 and was not available before Java 1.4. Instead, use the InputStreamReader and BufferedReader classes. It also has keyboard input, so import the IOException class.

Formatted output

Since Java5, by using the printf method, it is possible to easily display specifying formats such as specifying the number of digits and right-justification. The conversion characters can be specified in the following table. Relies on the C language printf.

Conversion characters

Conversion characters explanation
o Octal integer
d Decimal integer
x, X Output as hexadecimal integers
f Output as a decimal floating-point
s, S Display strings. For
c, C Display one character of char argument
t, T A prefix for date and time output. Specify the conversion type as %tm, %td, and so on
n Print OS-specific newline characters
% Prints the % character (¥u0025). If you want to display the % itself, write %%

Width and accuracy

System.out.printf("num[%5d]%n",12);  // num[   12]
System.out.printf("num[%5.1f]%n",12.3);  // num[ 12.3]


Flags can be used to specify a detailed display format.

Conversion characters explanation
'-' Left alignment.
'#' Use Alternate Form
'+' Always start with a + or -
' ' + If you prepend a space
',' Add locale-specific group delimiters.
'(' Enclose negative numbers in parentheses
'0' Padding the left side of the number with a 0 (0 fill)

Variable-length arguments

If you want to pass multiple arguments that are not arrays, use variable-length argument syntax. Only one variable-length argument can be defined for a method, and if it is defined as another argument, the last argument should be a variable-length argument.
public class PrintfSample {
    public static void main(String[] args) {

        System.out.printf("num[%5d]%n",12);         //  num[   12]
        System.out.printf("num[%5.1f]%n",12.3);     //  num[ 12.3]
        System.out.printf("num[%-5d]%n",12);        //  num[12   ]
        System.out.printf("num[%05d]%n",12);        //  num[00012]
        System.out.printf("num[%+5d]%n",12);        //  num[  +12]
        System.out.printf("num[%(5d]%n",-12);       //  num[ (12)]
        System.out.printf("num[%,5d]%n",1234568789);        //  num[1,234,568,789]
        System.out.printf("num[%#x]%n",0x12);       //  num[0x12




    static void listName(String... strs){
        for(String str : strs){


Author by

Updated on July 14, 2014