try~catch- 14.html

CODEDRAGON Development/JavaScript, jQuery, ...

반응형

   

try~catch

   

   

소스 코드

   

  1. <script type="text/javascript">
  2.                 function Rectangle(width, height){
  3.                         var width = width;             
  4.                         var height = height;
  5.                         this.getWidth = function(){
  6.                                 return width;
  7.                         };
  8.                         this.getHeight = function(){
  9.                                 return height;
  10.                         };
  11.                          
  12.                         this.setWidth = function(width){
  13.                                 if(width < 0){                                 
  14.                                         try{
  15.                                                 throw '길이는 음수일 없습니다';  
  16.                                         }catch(exception){
  17.                                                 console.log(exception);
  18.                                                 alert('음수를 입력할 없습니다.');
  19.                                         }                                      
  20.                                 }else{
  21.                                         width = width;
  22.                                 }
  23.                                  
  24.                         };
  25.                         this.setHeight = function(height){
  26.                                 //검증
  27.                                 if(height < 0){
  28.                                         try{
  29.                                                 throw '높이는 음수일 없습니다';  
  30.                                         }catch(exception){
  31.                                                 //콘솔에 로그 표시
  32.                                                 console.log(exception);
  33.                                                 alert('음수를 입력할 없습니다.');
  34.                                         }
  35.                                 }else{
  36.                                         height = height;
  37.                                 }
  38.                         };
  39.                 }
  40.                  
  41.                 Rectangle.prototype.getArea = function(){
  42.                         return this.getWidth() * this.getHeight();
  43.                 };
  44.                  
  45.                 var rectangle = new Rectangle(6, 8);           
  46.                 document.write('AREA = ' + rectangle.getArea() + '<br>');
  47.                  
  48.                 rectangle.setWidth(-5);
  49.                 document.write('AREA = ' + rectangle.getArea()+ '<br>');
  50.                            
  51.            
  52. </script>
  53. </head>
  54. <body>
  55.    
  56. </body>


   

 

출력결과

   

   

   

반응형