본문 바로가기

PHP/새로운문법

예외처리(try ~ catch)

<?php

    header("Content-Type: text/html; charset=UTF-8");


    function chkNum($num){

        if($num > 1){

            throw new Exception("숫자가 1보다 큼");

        }

        return true;

    }


    try{

        chkNum(2);

        print "숫자는 1보다 작음";

    }catch(Exception $e){

        print "메세지: ".$e->getMessage();

    }

?>






<?php

    header("Content-Type: text/html; charset=UTF-8");


    class customException extends Exception{

        public function errorMsg(){

            $errMsg = "에러 발생 라인: ".$this->getLine().",

                        에러파일: ".$this->getFile().",

                        에러메세지: ".$this->getMessage();

            return $errMsg;

        }

    }


    $email = "this@hhhh";


    try{

        if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){

            throw new customException($email);

        }

    }catch(customException $e){

        echo $e->errorMsg();

    }

?>