단비의 코딩 공부 blog

[Vanilla JS]study 22일차 - 에러 본문

javascript&jquery

[Vanilla JS]study 22일차 - 에러

황굽달 2023. 4. 17. 09:52

1. 오류코드

<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="UTF-8">
        <title>JS 에러</title>
    </head>
    <body>
        <script>
            aalert('안녕하세요');
        </script>
    </body>
</html>

2.try catch구문

<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="UTF-8">
        <title>JS 에러</title>
    </head>
    <body>
        <p id="test"></p>
        <script>
            //try{ } : 오류를 테스트할 구문을 작성
            //catch(에러객체){ } : 오류를 처리할 수 있는 구문

            const test = document.getElementById('test');

            try{
                aalert('안녕하세요'); //틀린상태
            }
            catch(err){
                //message : 에러 객체의 속성 - 오류메세지를 문자열로 설정해서 반환
                test.textContent = err.name;
            }
        </script>
    </body>
</html>

3. 에러 - 범위에러

<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="UTF-8">
        <title>JS 에러</title>
    </head>
    <body>
        <p id="test"></p>
        <script>
            //에러객체의 속성
            //1. name : 오류의 이름을 반환
            //2. message : 오류 메세지를 문자열로 반환

            //error name value
            //1. range error : 숫자에서 범위를 벗어나면 오류가 발생

            const test = document.getElementById('test');
           
            //임의적으로 숫자 1을 담는 변수
            let num = 1;
       
            try{
                //toPrecision() : 숫자를 지정된 길이로 형식화
                num.toPrecision(500); //숫자1은 한자리라서 에러
            }
            catch(err){
                test.textContent = err.name;
            }
        </script>
    </body>
</html>

4. 에러 - 참조에러

<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="UTF-8">
        <title>JS 에러</title>
    </head>
    <body>
        <p id="test"></p>
        <script>
            //에러객체의 속성
            //1. name : 오류의 이름을 반환
            //2. message : 오류 메세지를 문자열로 반환

            //error name value
            //2. reference error : 참조가 잘못되면 에러가 발생

            const test = document.getElementById('test');
           
            //y라는 변수를 선언하지 말고 수식으로 계산 처리
            let x;

            try{
                x = y + 10
            }
            catch(err){
                test.textContent = err.name;
            }
        </script>
    </body>
</html>

5. 에러 - 구문에러

<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="UTF-8">
        <title>JS 에러</title>
    </head>
    <body>
        <p id="test"></p>
        <script>
            //에러객체의 속성
            //1. name : 오류의 이름을 반환
            //2. message : 오류 메세지를 문자열로 반환

            //error name value
            //3. syntax error : 구문이 잘못되면 에러가 발생
            //4. eval error : eval() 함수가 잘못되면 오류가 발생 // 최신브라우저에서는 syntax 오류로 병합
            const test = document.getElementById('test');
           
            try{
                eval("alert('안녕하세요);");
            }            
            catch(err){
                test.textContent = err.name;
            }
        </script>
    </body>
</html>

6. 에러 - 타입에러

<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="UTF-8">
        <title>JS 에러</title>
    </head>
    <body>
        <p id="test"></p>
        <script>
            //에러객체의 속성
            //1. name : 오류의 이름을 반환
            //2. message : 오류 메세지를 문자열로 반환

            //error name value
            //5. type error : 데이터 타입이 잘못되면 에러발생
           
            // 숫자를 담는 변수
            let x = 100;

            try{
                x.toUpperCase();  //문자열을 대문자로 변경하는 메서드
            }
            catch(err){
                test.textContent = err.name;
            }
        </script>
    </body>
</html>

7. 에러 - URI에러

<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="UTF-8">
        <title>JS 에러</title>
    </head>
    <body>
        <p id="test"></p>
        <script>
            //에러객체의 속성
            //1. name : 오류의 이름을 반환
            //2. message : 오류 메세지를 문자열로 반환

            //error name value
            //6. URI error : URI 관련 함수를 잘못된 문자로 쓰는 경우 에러 발생

            const test = document.getElementById('test');

            try{
                decodeURI('%%%'); //잘못된 URI값 처리
            }  
            catch(err){
                test.textContent = err.name;
            }
        </script>
    </body>
</html>

8. throw 에러

<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="UTF-8">
        <title>JS 에러</title>
    </head>
    <body>
        <p>1~10사이의 숫자를 입력하세요.</p>
        <input type="text" id="numBox">
        <button id="btn">테스트</button>
        <p id="test"></p>
        <script>
            //throw : 사용자 지정 오류 만드는 구문
            //자바스크립트는 오류가 발생되면 일반적으로는 중지가 되고, 오류메시지가 생성
            //throw는 자바스크립트에 예외를 발생시켜 일부로 오류를 생성

            //입력상자에 1~10사이의 숫자를 입력한 것이 아닐 때 오류 발생
            //비어있음, 숫자가 아님, 숫자가 큰경우, 숫자가 작은경우

            //문서객체 선택
            const numBox = document.getElementById('numBox');
            const btn = document.getElementById('btn');
            const test = document.getElementById('test');

            btn.addEventListener('click', function(){
                //기존에 들어간 에러메시지 제거
                test.textContent = '';

                let v = numBox.value;

                try{
                    if(v == ''){
                        throw '비어있음';
                    }
                    if(inNan(v)){
                        throw '숫자가 아님';
                    }
                    if(v > 10){
                        throw '숫자가 큼'
                    }
                    if(v < 1){
                        throw '숫자가 작음'
                    }
                }
                catch(err){
                    test.textContent = '에러메시지 : ' + err;
                }
            });
        </script>
    </body>
</html>

9. 에러 - finally구문

<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="UTF-8">
        <title>JS 에러</title>
    </head>
    <body>
        <p>1~10사이의 숫자를 입력하세요.</p>
        <input type="text" id="numBox">
        <button id="btn">테스트</button>
        <p id="test"></p>
        <script>
            //finally{ } : 결과와 관계없는 try catch구문 후에 코드를 실행하는 구문

            //입력상자에 1~10사이의 숫자를 입력한 것이 아닐 때 오류 발생
            //비어있음, 숫자가 아님, 숫자가 큰경우, 숫자가 작은경우

            //문서객체 선택
            const numBox = document.getElementById('numBox');
            const btn = document.getElementById('btn');
            const test = document.getElementById('test');

            btn.addEventListener('click', function(){
                //기존에 들어간 에러메시지 제거
                test.textContent = '';

                let v = numBox.value;

                try{
                    if(v == ''){
                        throw '비어있음';
                    }
                    if(inNan(v)){
                        throw '숫자가 아님';
                    }
                    if(v > 10){
                        throw '숫자가 큼'
                    }
                    if(v < 1){
                        throw '숫자가 작음'
                    }
                }
                catch(err){
                    test.textContent = '에러메시지 : ' + err;
                }
                //위의 구문에 에러가 있든 없든 발생하고 싶은 코드를 작성
                //입력상자 값을 비우고, 입력상자에 다시 초점가게 처리
                finally{
                    numBox.value = '';
                    numBox.focus();
                }
            });
        </script>
    </body>
</html>