This vitally important question is addressed in the Catechism of the Catholic Church, no. 1257. Here is a summary of the Catechism’s nuanced teaching on this subject.
We must begin with the reality that we are conceived and born in a state of sin and alienation from God. This state of sin and alienation is called “original sin.” We are in need of redemption, and Christ is the one savior of the world (Acts 4:12). All salvation comes through Him alone.
Jesus clearly taught that we must be baptized in order to attain eternal life (Jn. 3:5). In addition, His final instruction, or “commission,” to His Apostles was that they make disciples of all nations, baptizing them in the name of the Father, and of the Son, and of the Holy Spirit (Mt. 28:19).
Based on Christ’s explicit teaching, the Church has always emphasized the need to be reborn as a child of God through Baptism in order to participate in His victory over sin and death.
The Church does not know of any means other than Baptism that assures entry into eternal life. Baptism is necessary for salvation for those to whom the Gospel has been proclaimed and who have had the opportunity to request the sacrament.
Yet, while God has bound salvation to the Sacrament of Baptism, He Himself is not bound by His sacraments. God can still bring about the salvation of the unbaptized who are faithful to the lights they have been given. As St. Peter said, “Truly I perceive that God shows no partiality, but in every nation anyone who fears him and does what is right is acceptable to him” (Acts 10:34-35).
The Church does not know with certainty the eternal destiny of infants who die without being baptized. She entrusts them to the great mercy of God (cf. Catechism, no. 1261).