18 [Instructor] Java Standards ch08

· Tech· Java
Java

| Hierarchy of program errors and exception classes

compile error

Runtime error: error Serious error - OOME(out of memory error)

exception

1) Occurred due to user error, etc. 2) Occurred due to programmer error (RuntimeException)

Logical error: behaves differently than intended


| Exception handling, try-catch statement flow

class Ex8_1 {

public static void main (String args[ ]) {

System.out.println(1);

try {

System.out.println(2);

System.out.println(3);

} catch (Exception e) { //No output because no exception occurred

System.out.println(4);

}

System.out.println(5);

}

}


class Ex8_2 {

public static void main (String args[ ]) {

System.out.println(1);

try {

System.out.println(0/0); //Exception occurred

System.out.println(2); //If an exception occurs, it goes to the catch block so there is no output.

} catch (ArithmeticException ae) {

System.out.println(3);

}

System.out.println(4);

}

}


class Ex8_4 {

public static void main (String args[ ]) {

System.out.println(1);

System.out.println(2);

try {

System.out.println(3);

System.out.println(0/0); //Exception occurred

System.out.println(4);

} catch (ArithmeticException ae) { //Skip the next catch block because it is applicable

if (ae instanceof ArithmeticException");

System.out.println("true");

System.out.println("ArithmeticException");

} catch (Exception e) { //Grand ancestor of all exceptions

System.out.println("Exception");

}

System.out.println(6);

}

}


| printStackTrace(), multi catch block

Exception object is created

Valid scope of reference variable ae

printStackTrace()

Displays method information and exception message in the call stack when an exception occurs on the screen.

getMessage()

Get the message stored in the instance of the exception class that occurred.

class Ex8_5 {

public static void main(String args[]) {

System.out.println(1);

System.out.println(2);

try {

System.out.println(3);

System.out.println(0/0);

System.out.println(4);

} catch (ArithmenticException ae) {

ae.printStackTrace();

//java.lang.ArithmethicException: /by zero at Ex8_5.main(Ex8_5.java:8)

System.out.println("Exception message: "+ae.getMessage());

//Exception message: / by zero

}

System.out.println(6);

}

}


Multi catch block

try {

.........

} catch ( Exception A | ExceptionB e ) {

e.printStackTrace();

//Parent, child relationship does not work, this can be solved by just declaring a parent type reference variable

//e.methodA() only for Exception A; Error when called, only common members are allowed

//Can be used after type conversion of instanceof

if(e instanceof ExeptionA) {

ExceptionA e1 = (ExceptionA)e;

e1.methodA();


| Raising an exception

Exception e = new Exception("intentional");

throw e;

//If there is no catch block, abnormal termination


checked exception

Unchecked exception: Exception handling is selected, no compilation error occurs even without a try-catch statement, and a runtime error occurs.


| Declaring an exception, finally block

Exception handling method: try-catch statement, declaring exception (passing over), hiding (empty catch block)

void method() throws Exception { } //Exception declaration, note that it is all exceptions

* Overriding

Declaration mismatch / Access controller not set narrowly / No more exception declarations than ancestors

When using the wait method, two exception handling is required in the throws part.

But only InterruptedException is required to handle exceptions! //Java API document

class Ex8_9 {

public static void main(String[] args) throws Exception {

method1();

}

static void method1() throws Exception {

method2();

static void method2() throws Exception {

throw new Exception();

}

}

//Exceptions passed from main are output from the JVM exception handler (at the time the exception occurs)


import java.io.*;

class Ex8_10 {

public static void main(String[] args) {

try {

File f = createFile(args[0]); //args[0] entered as a string

System.out.println(f.getName()+"The file was created successfully.");

catch (Exception e) {

System.out.println(e.getMessage()+"Please enter again.");

}

}

static File createFile (String fileName) throws Exception { //File creation, error declaration passed to main

if (fileName == null || fileName.equals(""))

throw new Exception("The file name is invalid.");

File f = new File(fileName); //Create an object of the File class

f.createNewFile(); //Create the actual file using the object's creatNewFile method

return f; //Returns a reference to the created object

}

}


finally

Write code that must be executed regardless of whether an exception occurs

Written at the bottom of the try-catch statement

try { startInstall(); copyFiles(); deleteTempFiles(); } catch (Exception e) { e.printStackTrace(); deleteTempFiles(); }

try { startInstall(); copyFiles(); } catch (Exception e) { e.printStackTrace(); } finally { deleteTempFiles(); } //Remove duplicates


| Creating custom exceptions and throwing exceptions

Ancestor chooses between Exception and RuntimeException

class MyException extends Exception {

MyException (String msg) {

super(msg); //조상의 Exception클래스의 생성자 호출


Throwing an exception

Raising an exception again after handling it, handled on both sides

public static void main(String[] args) {

try {

method1();

} catch (Exception e) {

System.out.println("An exception was handled in the main method.");

}

}

static void method1() throws Exception {

try {

throw new Exception();

} catch (Exception e) {

System.out.println("An exception was handled in method method1.");

throw e;

}

}


| linked exception

One exception (caused exception) can cause another exception.

public class Throwable implements Serializable { //Throwable is the ancestor of Exception and Error

.....

private Throwable cause = this ; //Register the object itself (this) as the cause exception

.....

private synchronized Throwable initCause(Throwable cause) { //Contains other exceptions, connected exceptions

.....

this.cause = cause ;

return this;

} .....

}


void install() throws InstallException {

try {

startInstall();

copyFiles();

} catch (SpaceException e) {

InstallException ie = new InstallException("Exception occurred during installation"); //Create exception

ie.initCause(e); // Specify the cause exception of InstallException as SpaceException

throw ie;

} catch (MemoryException me) {

.....


1. Since the catch block is too detailed, it is necessary to write and handle an exception connected to a single catch block.

→ Includes InstallException, SpaceException, and MemoryException

2. When trying to change a checked exception to an unchecked exception

→ Writing try-catch code can make the code unnecessarily long.

static void startInstall() throws SpaceException {

if(!enoughSpace())

throw new SpaceException("There is not enough space to install.");

if(!enoughMemory())

throw new RuntimeException (new MemoryException("Not enough memory."));

} //Register MemoryException as the cause exception of RuntimeException

Comments

No comments yet. Be the first!

    164 posts in 테크

    15 / 164