How Can I Force Execution to the Catch Block?

后端 未结 12 1303
野趣味
野趣味 2021-01-17 07:46

I am wondering can try..catch force execution to go into the catch and run code in there?

here example code:

try {
    if (         


        
12条回答
  •  南方客
    南方客 (楼主)
    2021-01-17 07:56

       try{
          if (AnyConditionTrue){
                  //run some code
                   }
          else{
                  throw new Exception();
              }
       }
       catch(){
    
          //run some code here...
    
       }
    

    But like Yuck has stated, I wouldn't recommend this. You should take a step back at your design and what you're looking to accomplish. There's a better way to do it (i.e. with normal conditional flow, instead of exception handling).

提交回复
热议问题