Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Exception handling using try...catch

class Main {
  public static void main(String[] args) {

    try {

      // code that generate exception
      int divideByZero = 5 / 0;
      System.out.println("Rest of code in try block");
    }
    
    catch (ArithmeticException e) {
      System.out.println("ArithmeticException => " + e.getMessage());
    }
  }
}
Comment

try and exception

def loan_emi(amount, duration, rate, down_payment=0):
    loan_amount = amount - down_payment
    try:
        emi = loan_amount * rate * ((1+rate)**duration) / (((1+rate)**duration)-1)
    except ZeroDivisionError:
        emi = loan_amount / duration
    emi = math.ceil(emi)
    return emi
Comment

exception handling

#include <iostream>
#include<conio.h>
using namespace std;
int main()
{
    int a=10, b=0, c;
    // try block activates exception handling
    try 
    {
        if(b == 0)
        {
            // throw custom exception
            throw "Division by zero not possible";
            c = a/b;
        }
    }
    catch(char* ex) // catches exception
    {
        cout<<ex;
    }
    return 0;
}
Comment

exception handling

@RestController
@RequestMapping("/product")
@AllArgsConstructor
public class ProductController {
  public static final String TRACE = "trace";

  @Value("${reflectoring.trace:false}")
  private boolean printStackTrace;
  
  private final ProductService productService;

  @GetMapping("/{id}")
  public Product getProduct(@PathVariable String id){
    return productService.getProduct(id);
  }

  @PostMapping
  public Product addProduct(@RequestBody @Valid ProductInput input){
    return productService.addProduct(input);
  }

  @ExceptionHandler(NoSuchElementFoundException.class)
  @ResponseStatus(HttpStatus.NOT_FOUND)
  public ResponseEntity<ErrorResponse> handleItemNotFoundException(
      NoSuchElementFoundException exception, 
      WebRequest request
  ){
    log.error("Failed to find the requested element", exception);
    return buildErrorResponse(exception, HttpStatus.NOT_FOUND, request);
  }

  @ExceptionHandler(MethodArgumentNotValidException.class)
  @ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
  public ResponseEntity<ErrorResponse> handleMethodArgumentNotValid(
      MethodArgumentNotValidException ex,
      WebRequest request
  ) {
    ErrorResponse errorResponse = new ErrorResponse(
        HttpStatus.UNPROCESSABLE_ENTITY.value(), 
        "Validation error. Check 'errors' field for details."
    );
    
    for (FieldError fieldError : ex.getBindingResult().getFieldErrors()) {
      errorResponse.addValidationError(fieldError.getField(), 
          fieldError.getDefaultMessage());
    }
    return ResponseEntity.unprocessableEntity().body(errorResponse);
  }

  @ExceptionHandler(Exception.class)
  @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  public ResponseEntity<ErrorResponse> handleAllUncaughtException(
      Exception exception, 
      WebRequest request){
    log.error("Unknown error occurred", exception);
    return buildErrorResponse(
        exception,
        "Unknown error occurred", 
        HttpStatus.INTERNAL_SERVER_ERROR, 
        request
    );
  }

  private ResponseEntity<ErrorResponse> buildErrorResponse(
      Exception exception,
      HttpStatus httpStatus,
      WebRequest request
  ) {
    return buildErrorResponse(
        exception, 
        exception.getMessage(), 
        httpStatus, 
        request);
  }

  private ResponseEntity<ErrorResponse> buildErrorResponse(
      Exception exception,
      String message,
      HttpStatus httpStatus,
      WebRequest request
  ) {
    ErrorResponse errorResponse = new ErrorResponse(
        httpStatus.value(), 
        exception.getMessage()
    );
    
    if(printStackTrace && isTraceOn(request)){
      errorResponse.setStackTrace(ExceptionUtils.getStackTrace(exception));
    }
    return ResponseEntity.status(httpStatus).body(errorResponse);
  }

  private boolean isTraceOn(WebRequest request) {
    String [] value = request.getParameterValues(TRACE);
    return Objects.nonNull(value)
        && value.length > 0
        && value[0].contentEquals("true");
  }
}
Comment

try catch error

// Main program passes in two ints, checks for errors / invalid input
// using template class type T for all variables within functions
#include <iostream>
using namespace std;

template <class T> // make function return type template (T)
void getMin(T val1, T val2)
{
    try
    {
        if (val1 < val2) // if val1 less than return it as min
            cout << val1 << " is the minimum
";
        else if (val1 > val2)
            cout << val2 << " is the minimum
";
        else 
            throw 505; // exception error processing when input is invalid
    }
    catch(T my_ERROR_NUM)
    {
        cout << "Input is invalid, try again. "; // first part of error message
    }
}

template <class T>
void getMax(T val1, T val2) // make function return type template (T)
{
    try
    {
        if (val1 > val2) // if val1 greater then return it as max
            cout << val1 << " is the maximum

";
        else if (val1 < val2)
            cout << val2 << " is the maximum

";
        else
            throw 505; // exception error processing when input is invalid
    }
    catch (T random_num)
    {
        cout << "Error 505!

"; // Second part of error messagee
    }
}
Comment

PREVIOUS NEXT
Code Example
Python :: syntax of ternary operator 
Python :: class object 
Python :: search object in array python 
Python :: dijkstra algorithm 
Python :: keras callbacks 
Python :: what is scaling 
Python :: print column name and index 
Python :: how to add space in python 
Python :: what is an indefinite loop 
Python :: Unreadable Notebook: jupyter 
Python :: deactivate pandas warning copy 
Python :: sum two linked lists if numbers are reversed in linked list 
Python :: randint without repitition 
Python :: python selenium class 
Python :: TypeError: Object of type DictProxy is not JSON serializable 
Python :: python - notification messages 
Python :: print A to Z in python uppercase 
Python :: same line print python 
Python :: restart device micropython 
Python :: destroy trigger python 
Python :: Create a matrix from a range of numbers (using arange) 
Python :: how to output varibles in python 
Python :: add service files in setup.py ROS2 
Python :: dataframe conditional formatting max values 
Python :: with statement python 3 files 
Python :: django query column 
Python :: what is certifi module in python 
Python :: pandas read csv skip until expression found 
Python :: how to convert string labels to numpy array 
Python :: spark dataframe without column 
ADD CONTENT
Topic
Content
Source link
Name
9+4 =