algorithm/java

java 개발이 처음일 때 볼 수 있는 에러

아르르르를를르 2021. 6. 2. 17:29

1. unreported exception java.io.IOException; must be caught or declared to be thrown

자바로 개발하다보면 어떤 예외처리는 반드시 개발자가 처리하도록 강요되는데 그 중 하나가 IOException 이다.

사용하는 method가 throw IOException하는 경우인데 Caller에서 처리해주지 않아 발생하는 에러다.

void Callee () throws java.io.IOException{

 

해결방안 1) Caller에서 try catch문으로 에러를 잡아주도록 한다.

try {
  Callee();
}
catch(IOException e) {
  e.printStackTrace();
}

 

해결방안 2) Caller에서 받은 에러를 다시 또 throws 하도록 한다.

이 경우 예외가 전달되고, 예외는 처리되지 않은 채 종료된다.

import java.io.IOException;

public class Main {
  public static void main(String[] args) throws IOException {
    Callee ioService = new Callee();
    ioService.read();
  }
}

 

 

2. Cannot make a static reference to the non-static field

public class Test{
    int i = 10;        
    
    void printTest(){
        System.out.println("Hi, There!");
    }
    
    public static void main(String[] args){        
        printTest();    
        i = 20;
    }    
}

static이 아닌 method나 field를 참조할 수 없다는 내용이다. JAVA는 static 맴버들이 먼저 compile 되기 때문에 static이 아닌 method나 field는 정의되지 않았기 때문이다. 따라서 모든 메소드나 필드를 static 맴버로 바꾸거나 new 객체를 생성해서 접근해야 한다.

 

해결방법 1) static 맴버로 모두 바꿔주기

public class Test{
    static int i = 10;   // static 변수로 선언      
    
    static void printTest(){
        System.out.println("Hi, There!");
    }
    
    public static void main(String[] args){        
        printTest();    
        i = 20;
    }    
}

 

해결방법 2) 해당 class 객체를 따로 생성

public class Test{
    int i = 10;        
    
    void printTest(){
        System.out.println("Hi, There!");
    }
    
    public static void main(String[] args){
        Test test;
        test = new Test(); // 새 객체 생성
        
        test.printTest();    
        test.i = 20;
    }    
}

 



출처: https://imasoftwareengineer.tistory.com/89, https://wookoa.tistory.com/80

'algorithm > java' 카테고리의 다른 글

hackerrank/warm up/Repeated String  (0) 2021.06.20
hackerranck/warm up/jumping on the clouds  (0) 2021.06.13
hackerrank/warm up/Counting Valleys  (0) 2021.05.23
java 조건문 사잇값  (0) 2021.05.18
hackerranck/warmup/Sales by Match  (0) 2021.05.16