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).
try{
//...
}catch(NumberFormatException e){
//...
}finally{
//必ず実行される
}
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
try{
}catch(Exception e){
e.printStackTrace();
//こういう書き方でも出力される
System.out.println(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, java.io.IOException
- 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.
Specifically
- Exception try{...} catch{...} Catch in
- 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) {
System.out.println("処理開始");
sleep2s();
System.out.println("処理終了");
}
static void sleep2s(){
try{
Thread.sleep(2000);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
public class ThreadSample2 {
public static void main(String[] args) throws InterruptedException {
System.out.println("処理開始");
sleep2s();
System.out.println("処理終了");
}
static void sleep2s() throws InterruptedException{
Thread.sleep(2000);
}
}
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.
log
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(System.in);
System.out.println("何か入力してください。");
if(sc.hasNextDouble()){
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 = sc.next();
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(System.in);
System.out.println("何か繰り返し入力してください。");
while(sc.hasNext()){
String s = sc.next();
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]
flag
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) {
//フラグサンプル。num[]%nの形式は、わかりやすくするために含めている
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
//複数の引数と、引数番号のサンプル
//引数順序を変更したい場合は、引数の番号+$をつけて指定する(1$,2$,....,n$)
System.out.printf("num1=%d,num2=%d%n",10,20);
System.out.printf("num1=%2$d,num2=%1$d%n",10,20);
//可変長変数メソッド呼び出しサンプル
listName("hoge","fuga","foo","bar");
}
//可変長変数のメソッド定義サンプル
static void listName(String... strs){
for(String str : strs){
System.out.println(str);
}
}
}